简体   繁体   中英

Map array of objects based on Id

Noob javascript enthusiast here.

I'm trying to understand the various higher-order functions of javascript, and am particularly curious with the possibilities of.map() on an array of objects.

Suppose you have the following:

selectedId = ['u1', 'u2']
data = [
{id: 'u1', color: 'red', age: '24'},
{id: 'u2', color: 'blue', age: '18'},
{id: 'u3', color: 'yellow', age: '15'}
]

How would you go about creating a new array that only contains the object of u1 and u2? Ie:

selectedData = [
{id: 'u1', color: 'red', age: '24'},
{id: 'u2', color: 'blue', age: '18'},
]

You would have to Array#map over your selectedId array, then find corresponding object inside data array using Array#find .

 const selectedId = ['u1', 'u2']; const data = [ {id: 'u1', color: 'red', age: '24'}, {id: 'u2', color: 'blue', age: '18'}, {id: 'u3', color: 'yellow', age: '15'} ]; const res = selectedId.map((id) => data.find((o) => o.id === id)); console.log(res);

If I understand it correctly, You can use array filter like

data.filter(el => selectedId.includes(el.id));

would give

[
{id: 'u1', color: 'red', age: '24'},
{id: 'u2', color: 'blue', age: '18'}
]

Or alternatively

selectedId.map((id) => data.find((el) => el.id === id));

would give

[
{id: 'u1', color: 'red', age: '24'},
{id: 'u2', color: 'blue', age: '18'}
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM