0

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

1 Answer 1

5

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Damn that looks so simple. Thank you
@mplungjan Sure

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.