Shawn Sheehan
Shawn Sheehan

Reputation: 191

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'}
           ]} 

Upvotes: 0

Views: 34

Answers (1)

gurvinder372
gurvinder372

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

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

Upvotes: 5

Related Questions