Consider the following data:
let data = [
{ foo: true, bar: [ 1, 2, 3 ] },
{ foo: true, bar: [ 8, 9, ] }
];
I'm trying to push
something to the nested bar
array on index 1
using the spread syntax (...
).
So the final array should become:
[
{ foo: true, bar: [ 1, 2, 3 ] },
{ foo: true, bar: [ 8, 9, 'new-item' ] }
]
Normally, we'll just use push: data[1].bar.push(0)
, but I need a spread solution
I've tried to use this approach:
How to push new elements to a nested array of objects in JavaScript using spread syntax
data = [ ...data, {[1]: { ...data[1], bar: [ ...data[1].bar, 'new-item' ] } }]
But this will append another object with a single key 1
, it does not alter data[1]
.
Then, I've tried to use Object.assign()
but again ended up with a new index:
Replace array entry with spread syntax in one line of code?
data = [ ...data, Object.assign({}, data[1], { bar }})
tl;dr, How do I append something to an array, part of an object, that's inside an array of objects, using the spread syntax?
Please link me to a duplicate, or provide a way to do this
Playground:
let data = [
{ foo: true, bar: [ 1, 2, 3 ] },
{ foo: true, bar: [ 8, 9 ] }
];
// 'Regular' push method
// data[1].bar.push(0);
// Using spread reassign
// data = [ ...data, {[1]: { ...data[1], bar: [ ...data[1].bar, 'new-item' ] } }]
// Using Object.assign
data = [ ...data, Object.assign({}, data[1], {bar: [ 'new-item' ] } ) ];
console.log(data)