I want to take an existing array and add it to the existing array of Objects. I want to add a new key with values from reasons. Please help.
Array:
const reasons = [‘a’, ‘b’, ‘c’];
Object of arrays that look like:
[{id: 1,
Data: ‘yes’
active: true
},
{id: 2,
Data: ‘yes’
active: false
},
{id: 3,
Data: ‘data’
active: false
}]
Result want:
[{
id: 1,
Data: ‘yes’,
active: true,
reason: a
},
{id: 2,
Data: ‘yes’,
active: false,
reason: b
},
{id: 3,
Data: ‘data’
active: false
reason: c
}]
3
Answers
Simplest way is to loop through each object and add
reason
to itA simple
map
function can accomplish this for you.The new value of
merged
:I hope that’s what you were going for and that this helped.
You can achieve this by mapping over your existing array of objects and adding the values from the
reasons
array to each object. Here’s a simple way to do this in JavaScript:Example:
Output: