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.


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)

您可以使用unshift()将项目添加到数组的开头

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

console.log(oldArray);
链接地址: http://www.djcxy.com/p/19368.html

上一篇: 在javascript对象中推送和不移位操作

下一篇: 使用扩展运算符将对象添加到数组的开头