1

I've a list

let data = [{order: 1, plannedid:32, userid:123 },
            {order: 2, plannedid:33, userid:124 }];
let keys = ['orderid','plannerid'];

based on the keys we need to get all the columns from the array.

I'm able to get the data as expected with the below code,

let tempData =[];
 data.forEach(function(d) {
            tempData.push({
              orderid: d.orderid,
              plannerid: d.plannerid
            });
          });

Output:

[{order: 1, plannedid:32},
{order: 2, plannedid:33 }];

but if my keys array is dynamic how can we read based on the key

ex: let keys = ['orderid','userid'];

can we add condition into Push function

0

1 Answer 1

6

You could map the keys for new objects.

const
    data = [{ order: 1, plannedid: 32, userid: 123 }, { order: 2, plannedid: 33, userid: 124 }],
    keys = ['order', 'plannedid'];
    result = data.map(o => Object.fromEntries(keys.map(k => [k, o[k]])));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.