Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing dynamic keys from array of objects

This previous question comes closest to what I am curious of. I've tried several variations of indexOf() and filter() to no success

I have an arrays of objects (exampleDat):

[{id:1, value:"100", name:"dog", D1: 10, D2: 67, D3: 33},
{id:2, value:"200", name:"cat", D1: 66, D2: 41, D3: 34},
{id:3, value:"300", name:"fish", D1: 23, D2: 45, D3:},
{id:4, value:"400", name:"mouse", D1: 13, D2: 55, D3:},
{id:5, value:"500", name:"snake", D1: 7, D2: 9, D3:}]

In a different function, I return an array of which of these 'keys' I need. This array changes dynamically, so its not possible to type them all out. For example any of the following examples are viable,

useThese1 = ['D1','D2'] //Want exampleDat returned with only these key,value 'columns' returned
useThese2 = ['id','D1','D2','D3'] //Want exampleDat return with only these key,value 'columns' returned
useThese3 = ['value','D2','D3'] //Want exampleDat returned with only these key,value 'columns' returned

So I need to dynamically map the values in a useThese array to the exampleDat array

If I knew the exact columns, I could hand type it ala:

exampleDat.map(d => {return {D1: d.D1, D2: d.D2}})

But I need something like:

dat.map(d => useThese1.map(g =>  {return {something?}}) ???

In R, it would simply and easily be exampleDat[,colnames(exampleDat) %in% useThese1]

like image 932
K.J.J.K Avatar asked Dec 31 '22 09:12

K.J.J.K


1 Answers

You could map the new keys.

const
    mapWith = (array, keys) => array.map(o => Object.fromEntries(keys.map(k => [k, o[k]]))),
    data = [{ id: 1, value: "100", name: "dog", D1: 10, D2: 67, D3: 33 }, { id: 2, value: "200", name: "cat", D1: 66, D2: 41, D3: 34 }, { id: 3, value: "300", name: "fish", D1: 23, D2: 45, D3:97}, { id: 4, value: "400", name: "mouse", D1: 13, D2: 55, D3:98}, { id: 5, value: "500", name: "snake", D1: 7, D2: 9, D3:99}],
    result1 = mapWith(data, ['D1', 'D2']),
    result2 = mapWith(data, ['id', 'D1', 'D2', 'D3']),
    result3 = mapWith(data, ['value', 'D2', 'D3']);

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

Object.fromEntries are relatively recent, but easily polyfilled.

like image 94
Nina Scholz Avatar answered Jan 05 '23 19:01

Nina Scholz