考虑以下数据:
let data = [
{ foo: true, bar: [ 1, 2, 3 ] },
{ foo: true, bar: [ 8, 9, ] }
];
我正在尝试使用 spread syntax (...
)。
所以最终的数组应该变成:
[
{ foo: true, bar: [ 1, 2, 3 ] },
{ foo: true, bar: [ 8, 9, 'new-item' ] }
]
通常情况下,我们只会使用推送: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;dr,如何使用展开语法将某些内容附加到对象数组内的数组(对象的一部分)?
请将我链接到副本,或提供执行此操作的方法
Playground :
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)
最佳答案
您可以采用一个外部 Object.assign
,其中一个数组作为目标,一个对象的索引作为键。
let
data = [
{ foo: true, bar: [1, 2, 3] },
{ foo: true, bar: [8, 9] }
];
data = Object.assign(
[...data], // target array
{ 1: { // array index as key
...data[1],
bar: [...data[1].bar, 'new-item']
} }
);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于Javascript 将数组索引扩展到 'push' 新项目到嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75175058/