对象数组,push后移除数组,保留对象
Array of objects, remove the array after push, keep objects
我试图将我的对象数组推送到变量中,但我收到的只是数组中的数组或单个对象。
myObject = {
id: id,
items: [],
boolean: true,
}
myArray = [{1}, {2}, {3}]
我试过 myObject.items.push(myArray[0])
但这个 returns 只是第一个对象。没有 0 它的双数组。
我要的是
myObject = {
id: id,
items: [{1}, {2}, {3}],
boolean: true,
}
您在这里要做的是将整个数组设置为新值,如下所示:
myObject.items = myArray
如果你想采用不可变的方法,那么你可以像这样复制它:
myObject.items = [...myArray]
编辑:
如果您想向 myObject.items
添加项目(而不仅仅是完全覆盖),那么您应该这样做:
myObject.items = [...myObject.items, ...myArray]
这会将您的新数组项添加到当前项数组的末尾,您也可以这样做以将它们添加到开头:
myObject.items = [...myArray, ...myObject.items]
你可以用这个
myObject.items.push(...myArray)
正如 Andreas 评论的那样,另一种解决方案是使用 concat。 Concat 类似于 push
。但它实际上并没有改变数组,它 returns 一个新的。
const x = []
console.log(x.concat(3)) // prints [3]
console.log(x) // prints []
通常需要这种行为,因为它可以防止“副作用”的发生
它也不只是将项目附加到数组,它仅在项目不是数组时才执行此操作。如果它是一个数组,它将合并两个数组
const x = [1,2,3]
console.log(x.concat([4,5,6]) // prints [1,2,3,4,5,6]
所以这里的解决方案是
myObject.items = myObject.items.concat(myArray)
//object
myObject={
id:1,
items:[],
boolean: true
}
//concat
myArray = [ 1,2,3];
myObject.items += myArray;
console.log(myObject.items);
我试图将我的对象数组推送到变量中,但我收到的只是数组中的数组或单个对象。
myObject = {
id: id,
items: [],
boolean: true,
}
myArray = [{1}, {2}, {3}]
我试过 myObject.items.push(myArray[0])
但这个 returns 只是第一个对象。没有 0 它的双数组。
我要的是
myObject = {
id: id,
items: [{1}, {2}, {3}],
boolean: true,
}
您在这里要做的是将整个数组设置为新值,如下所示:
myObject.items = myArray
如果你想采用不可变的方法,那么你可以像这样复制它:
myObject.items = [...myArray]
编辑:
如果您想向 myObject.items
添加项目(而不仅仅是完全覆盖),那么您应该这样做:
myObject.items = [...myObject.items, ...myArray]
这会将您的新数组项添加到当前项数组的末尾,您也可以这样做以将它们添加到开头:
myObject.items = [...myArray, ...myObject.items]
你可以用这个
myObject.items.push(...myArray)
正如 Andreas 评论的那样,另一种解决方案是使用 concat。 Concat 类似于 push
。但它实际上并没有改变数组,它 returns 一个新的。
const x = []
console.log(x.concat(3)) // prints [3]
console.log(x) // prints []
通常需要这种行为,因为它可以防止“副作用”的发生
它也不只是将项目附加到数组,它仅在项目不是数组时才执行此操作。如果它是一个数组,它将合并两个数组
const x = [1,2,3]
console.log(x.concat([4,5,6]) // prints [1,2,3,4,5,6]
所以这里的解决方案是
myObject.items = myObject.items.concat(myArray)
//object
myObject={
id:1,
items:[],
boolean: true
}
//concat
myArray = [ 1,2,3];
myObject.items += myArray;
console.log(myObject.items);