MorphicPro
MorphicPro

Reputation: 2902

Select objects from an array of objects with an array of ids javascript

say I have a list of objects like so.

const list = [{id: 1, name: "foo"}, {id: 2, name: "bar"}, {id: 3, name: "baz"}]

And then I have a list of items I'd like to find in said list.

const ids = [1, 3]

how can I return an array of objects that match the ids found in ids from list using javascript?

heres an example of the return I'd like to see given I have [1, 3].

-> [{id: 1, name: "foo"}, {id: 3, name: "baz"}]

Thanks - Josh

Upvotes: 2

Views: 1064

Answers (2)

Kosh
Kosh

Reputation: 18378

You can do it with map and find:

const list = [{id: 1, name: "foo"}, {id: 2, name: "bar"}, {id: 3, name: "baz"}];
const ids = [1, 3];
const newArr = ids.map(i => list.find(({id}) => i === id));
console.log(newArr);

Upvotes: 0

P.S.
P.S.

Reputation: 16384

You can do it via filter method, which returns new array of items, based on condition you wrote inside. I also recommend to use includes method to check, whether your array of ids has such item:

const list = [{id: 1, name: "foo"}, {id: 2, name: "bar"}, {id: 3, name: "baz"}];
const ids = [1, 3];
const newArr = list.filter(item => ids.includes(item.id));
console.log(newArr);

Upvotes: 5

Related Questions