Home > Blockchain >  How to inject a new property into a JavaScript spread operator
How to inject a new property into a JavaScript spread operator

Time:04-19

I am attempting to update an existing array of objects by adding a new object:

const oldArray = [{ name: 'First', value: 'one' }, { name: 'Second', value: 'two' }, { name: 'Third', value: 'three' }]
const newArray = [...oldArray, { name: 'Fourth', value: 'four' }]

My intention, however, is to set up newArray so that the Fourth object becomes the 3rd item (index 2) in oldArray. How can I go about setting up newArray so that the new object is injected as the 3rd item in the ...oldArray spread operator, without having to write out all of the oldArray items again in newArray?

CodePudding user response:

You can use .slice() along with the spread syntax.

const oldArray = [{ name: 'First', value: 'one' }, { name: 'Second', value: 'two' }, { name: 'Third', value: 'three' }]
const newArray = [...oldArray.slice(0, 2), { name: 'Fourth', value: 'four' }, ...oldArray.slice(2)];

console.log(newArray);

CodePudding user response:

You would need to do two spreads using slice

const oldArray = [{ name: 'First', value: 'one' }, { name: 'Second', value: 'two' }, { name: 'Third', value: 'three' }]
const newArray = [...oldArray.slice(0,2), { name: 'Fourth', value: 'four' }, ...oldArray.slice(2)]

console.log(newArray.map(x => x.name));

other option is to just use splice()

const oldArray = [{ name: 'First', value: 'one' }, { name: 'Second', value: 'two' }, { name: 'Third', value: 'three' }]
const newArray = [...oldArray]
newArray.splice(2,0,{ name: 'Fourth', value: 'four' });

console.log(newArray.map(x => x.name));

  • Related