Reputation: 1991
I have a JS object like this:
const myObj = {
'$prop1': 1,
'$prop2': 2,
'$prop3': 3
};
and an array of object like this:
const myArray = [
{
prop1: 'some stuff',
prop2: 'some other stuff',
propKey: '$prop1'
},
{
prop1: 'some stuff',
prop2: 'some other stuff',
propKey: '$prop2'
},
{
prop1: 'some stuff',
prop2: 'some other stuff',
propKey: '$prop5'
},
];
I am trying to write a function fo filter myObj and only get the fields I can find in myArray.propKey.
this is what I tried so far with no luck:
export const filterVariantContentByColumns = (myObj, myArray) => {
const objArray = Object.keys(myObj).map(i => myObj[i]);
return objArray.filter(value => myArray.includes(value.key_name));
console.log(res);
};
any idea how to do that please?
Upvotes: 0
Views: 48
Reputation: 3228
Another answer.
const myObj = {
'$prop1': 1,
'$prop2': 2,
'$prop3': 3,
'$prop4': 4
};
const myArray = [
{
prop1: 'some stuff',
prop2: 'some other stuff',
propKey: '$prop1'
},
{
prop1: 'some stuff',
prop2: 'some other stuff',
propKey: '$prop2'
},
{
prop1: 'some stuff',
prop2: 'some other stuff',
propKey: '$prop5'
},
];
let propKeys = myArray.map(ele => ele.propKey)
let obj = Object.keys(myObj).reduce((ret, key) => {
if (propKeys.indexOf(key) > -1) {
ret[key] = myObj[key]
}
return ret
}, {})
console.log(obj)
Upvotes: 0
Reputation: 370729
Turn the myArray
into a Set of propKey
s first, then filter myObj
by whether the key being iterated over is in the Set:
const myObj = {
'$prop1': 1,
'$prop2': 2,
'$prop3': 3
};
const myArray = [
{
prop1: 'some stuff',
prop2: 'some other stuff',
propKey: '$prop1'
},
{
prop1: 'some stuff',
prop2: 'some other stuff',
propKey: '$prop2'
},
{
prop1: 'some stuff',
prop2: 'some other stuff',
propKey: '$prop5'
},
];
const haveKeys = new Set(myArray.map(({ propKey }) => propKey));
const output = Object.entries(myObj)
.filter(([key]) => haveKeys.has(key))
console.log(output);
Upvotes: 0
Reputation: 386578
You could iterate the array and map found properties.
const
myObj = { $prop1: 1, $prop2: 2, $prop3: 3 },
myArray = [{ prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop1' }, { prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop2' }, { prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop5' }],
result = myArray.flatMap(({ propKey }) => propKey in myObj ? myObj[propKey] : []);
console.log(result);
With keys
const
myObj = { $prop1: 1, $prop2: 2, $prop3: 3 },
myArray = [{ prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop1' }, { prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop2' }, { prop1: 'some stuff', prop2: 'some other stuff', propKey: '$prop5' }],
result = Object.fromEntries(myArray.flatMap(({ propKey }) => propKey in myObj ? [[propKey, myObj[propKey]]] : []));
console.log(result);
Upvotes: 1