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

Sivamohan Reddy
  • 436
  • 1
  • 8
  • 26

1 Answers1

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392