I have
let list = {
1: { name: "someone1" },
5: { name: "someone5" },
7: { name: "someone7" },
8: { name: "someone8" }
};
and I want to filter [1,5,42]
[
{ name: "someone1" },
{ name: "someone5" }
]
I tried
Object.keys(list).map(key=> {if([1,5,42].includes(key)) return list[key]});
[
{ name: "someone1" },
{ name: "someone5"},
undefined,
undefined
]
PS: When my list was a json array, I used list.filter(person => [1,5].includes(person.id))
. I then changed to keyed by id model, so I can use liat[id]
which is way faster than list.filter for single element.
You could directly iterate the filter array and take the object.
You need a different approach, if the filter contains strings, which are not keys of the object.
A two step solution with mapping values of the object and filtering with
Boolean
for truthy elements.this solution assumes you only ask for existing keys.
You can use destructuring assignment
A one-liner solution:
Nina Scholz's simple one liner:
[1,5,42].reduce((r, k) => r.concat(list[k] || []), []);
is different in that it checks before adding it to the array while the above one removesundefined
s after building the array.One more possible one-liner would be:
Snippet: