简体   繁体   中英

Map through new array then push items to objects in exisiting array

If I have one main array which exists like so.

arr = {
    people:[{name: 'Zero'},{name: 'Jeans'},{name: 'Duct'}]
}

And I want to map over an array of colors and assign each object in the array a color from this array.

colors = { color: ['#fff', '#fa0', '#eee'] }

How would this be achieved?

I can map through arr.people then map colors.color but no luck.

Would like to end up with this

 arr = {
    people:[{name: 'Zero', color: '#FFF'},
            {name: 'Jeans', color: '#FA0'},
            {name: 'Duct', color: '#EEE'}
           ]} 

Use map

arr.people = arr.people.map( (s, i) => ({...s, color: colors.color[i]}) )

Demo

 var arr = { people: [{ name: 'Zero' }, { name: 'Jeans' }, { name: 'Duct' }] }; var colors = { color: ['#fff', '#fa0', '#eee'] }; arr.people = arr.people.map((s, i) => ({ ...s, color: colors.color[i] })); console.log(arr); 

Explanation

  • Iterate arr.people using map
  • Return an object from each iteration having an extra property - color using spread syntax .

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