Reputation: 191
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'}
]}
Upvotes: 0
Views: 34
Reputation: 68443
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
arr.people
using map
color
using spread syntax.Upvotes: 5