Add object to the beginning of array using spread operator Add object to the beginning of array using spread operator reactjs reactjs

Add object to the beginning of array using spread operator


I'm a little late but

You can solve this problem modifying it like this with spreed:

change:

var result = [newObj, ...oldArray]

for:

var result = [{...newObj}, ...oldArray]


You could use the unshift() function which does exactly that:

let oldArray = [{'value': '1', 'label': 'a'}, {'value': '2', 'label': 'b'}]let newObj = {'value': 'all', 'label': 'all'}oldArray.unshift(newObj)console.log(oldArray)

Or if you don't want to modify the original array, you can do:

const result = oldArray.slice()result.unshift(newObj)console.log(result)


You can use unshift() to add items to the beginning of an array

var oldArray = [{'value': '1', 'label': 'a'}, {'value': '2', 'label': 'b'}]var newObj = {'value': 'all', 'label': 'all'}oldArray.unshift(newObj);console.log(oldArray);