【发布时间】:2023-01-20 00:20:35
【问题描述】:
考虑以下数据:
let data = [
{ foo: true, bar: [ 1, 2, 3 ] },
{ foo: true, bar: [ 8, 9, ] }
];
我正在尝试使用 spread syntax (...) 将 push 的内容添加到索引 1 上的嵌套 bar 数组。
所以最终的数组应该变成:
[
{ foo: true, bar: [ 1, 2, 3 ] },
{ foo: true, bar: [ 8, 9, 'new-item' ] }
]
一般情况下,我们直接push:data[1].bar.push(0),但是我需要一个传播方案
我试过使用这种方法:
How to push new elements to a nested array of objects in JavaScript using spread syntax
data = [ ...data, {[1]: { ...data[1], bar: [ ...data[1].bar, 'new-item' ] } }]
但这将附加另一个具有单个键1的对象,它不会改变data[1]。
然后,我尝试使用Object.assign(),但又得到了一个新索引:
Replace array entry with spread syntax in one line of code?
data = [ ...data, Object.assign({}, data[1], { bar }})
tl;博士,我如何将一些东西附加到一个数组,一个对象的一部分,它位于一个对象数组中,使用传播语法?
请将我链接到副本,或提供一种方法来执行此操作
操场:
let data = [
{ foo: true, bar: [ 1, 2, 3 ] },
{ foo: true, bar: [ 8, 9 ] }
];
// 'Regular' push method
// data[1].bar.push(0);
// Using spread reassign
// data = [ ...data, {[1]: { ...data[1], bar: [ ...data[1].bar, 'new-item' ] } }]
// Using Object.assign
data = [ ...data, Object.assign({}, data[1], {bar: [ 'new-item' ] } ) ];
console.log(data)
【问题讨论】:
-
我没有发布答案,但这似乎有效:
data = [ data[0], { ...data[1], bar: [ ...data[1].bar, 'new-item' ] } ]
标签: javascript arrays spread