Add object to the beginning of array using spread operator

Diego Unanue picture Diego Unanue · Apr 28, 2017 · Viewed 9.4k times · Source

I have an array like this:

var oldArray = [{'value': '1', 'label': 'a'}, {'value': '2', 'label': 'b'}]

what I want is using spread operator add a new object at the beginning of that array:

BTW this works:

var oldArray = [{'value': '1', 'label': 'a'}, {'value': '2', 'label': 'b'}]
var newObj = {'value': 'all', 'label': 'all'}
var result = [newObj, ...oldArray]

But generates a key "newObj" like this:

var oldArray = [newObj : {'value': 'all', 'label': 'all'}, 0: {'value': '1', 'label': 'a'}, 1:{'value': '2', 'label': 'b'}]

And I want the key to be auto generated like if I do this:

var result = [{'value': 'all', 'label': 'all'}, ...oldArray]

And imagine the result is this:

var oldArray = [newObj : {0: 'all', 'label': 'all'}, 1: {'value': '1', 'label': 'a'}, 2:{'value': '2', 'label': 'b'}]

but that gives me an error.

Right now I'm using unshift and it works, I wonder if there's a way to do the same with spread operator.

Answer

Reyes Richard picture Reyes Richard · Aug 26, 2020

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]