0

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?

JS_is_awesome18
  • 1,587
  • 7
  • 23
  • 67
  • 2
    seems like you want splice if you want to control where it is added. – epascarello Apr 18 '22 at 15:34
  • 1. [There is no spread **operator**](https://stackoverflow.com/questions/44934828/is-it-spread-syntax-or-the-spread-operator). 2. Why exactly do you expect to use spread here at all? – VLAZ Apr 18 '22 at 15:36

2 Answers2

1

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);
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

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));
epascarello
  • 204,599
  • 20
  • 195
  • 236