繁体   English   中英

Javascript 在数组索引上传播以将新项目“推送”到嵌套数组

[英]Javascript spread on array index to 'push' new item to nested array

考虑以下数据:

let data = [
    { foo: true, bar: [ 1, 2, 3 ] },
    { foo: true, bar: [ 8, 9,   ] }
];

我正在尝试使用扩展语法( ... ) 将某些内容push送到索引1上的嵌套bar数组。

所以最终的数组应该变成:

[
    { foo: true, bar: [ 1, 2, 3 ] },
    { foo: true, bar: [ 8, 9, 'new-item'  ] }
]

通常,我们只使用 push: data[1].bar.push(0) ,但我需要一个传播解决方案


我试过使用这种方法:
如何使用扩展语法将新元素推送到 JavaScript 中的嵌套对象数组

data = [ ...data, {[1]: { ...data[1], bar: [ ...data[1].bar, 'new-item' ] } }] 

但这将 append 另一个 object 与一个键1 ,它不会改变data[1]


然后,我尝试使用Object.assign()但又得到了一个新索引:
在一行代码中用扩展语法替换数组条目?

data = [ ...data, Object.assign({}, data[1], { bar }})

tl; dr ,我如何使用扩展语法将 append 的内容添加到数组中,这是 object 的一部分,它位于对象数组中?

请将我链接到副本,或提供一种方法来执行此操作


操场:

 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与一个数组作为目标,并将一个 object 与索引作为键。

 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; }

您可以在数组本身上使用Object.assign

 let data = [ { foo: true, bar: [ 1, 2, 3 ] }, { foo: true, bar: [ 8, 9, ] } ]; data = Object.assign([...data], {1: {...data[1], bar: [...data[1].bar, 'new-item']}}); console.log(data);

我不认为这比向您开放的许多其他选项更具可读性,但这满足了“使用 object 传播”的要求。

 let data = [ { foo: true, bar: [ 1, 2, 3 ] }, { foo: true, bar: [ 8, 9, ] }, { foo: false, bar: [ ] } ]; let idx = 1; let newData = [...data.slice(0, idx), {...data[idx], bar: [...data[idx].bar, 'new-item' ] }, ...data.slice(idx+1) ]; console.log(newData);

这将首先获取您的数据并将数组剪切到您要替换的项目(索引 1)。 接下来是一个新的 object,然后是数组(如果有)的 rest。

首先,将数组视为带有编号键的 object,并使用扩展运算符并覆盖必要的索引。 然后,使用 Object.values() 将其视为数组。

 let data = [ { foo: true, bar: [ 1, 2, 3 ] }, { foo: true, bar: [ 8, 9, ] } ] data = Object.values({...data, 1: {...data[1], bar: [...data[1].bar, 'new-item' ] } }) console.log(data)

在这种特殊情况下,如果您需要更改的索引靠近数组的开头,您还可以使用 IIFE 来实现解构方法,如下所示:

 let data = [ { foo: true, bar: [ 1, 2, 3 ] }, { foo: true, bar: [ 8, 9, ] } ] data = (([first, {bar, ...rest}]) => [first, {...rest, bar:[...bar, 'new-item']}])(data) console.log(data)

您可以将第一个元素索引分配给使用Array#map和扩展运算符的修改元素,如下所示:

 const data = [ { foo: true, bar: [ 1, 2, 3 ] }, { foo: true, bar: [ 8, 9, ] } ]; data[1] = [data[1]].map(({foo,bar}) => ({foo,bar:[...bar,"some new value"]}))[0]; console.log( data );

暂无
暂无

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

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