Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add object to the beginning of array using spread operator

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.

like image 872
Diego Unanue Avatar asked Apr 28 '17 14:04

Diego Unanue


People also ask

How do I add an item to the beginning of an array?

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

How do you create a new object using the spread operator?

The fundamental idea of the object spread operator is to create a new plain object using the own properties of an existing object. So {... obj} creates a new object with the same properties and values as obj . For plain old JavaScript objects, you're essentially creating a copy of obj .

How do you add an object to an array?

The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.


3 Answers

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]
like image 147
Reyes Richard Avatar answered Oct 26 '22 15:10

Reyes Richard


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);
like image 27
George Avatar answered Oct 26 '22 16:10

George


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)
like image 37
AP. Avatar answered Oct 26 '22 15:10

AP.