简体   繁体   English

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

[英]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:但是会像这样生成一个关键的“newObj”:

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.现在我正在使用 unshift 并且它有效,我想知道是否有办法对扩展运算符执行相同的操作。

I'm a little late but我有点晚了但是

You can solve this problem modifying it like this with spreed:您可以使用 spreed 像这样修改它来解决这个问题:

change:改变:

var result = [newObj, ...oldArray]

for:为了:

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

You could use the unshift() function which does exactly that:您可以使用unshift()函数来执行此操作:

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您可以使用unshift()将项目添加到数组的开头

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM