如何使用Spread语法向数组指定索引对象的bar数组添加新项
问题:使用扩展语法(spread)向嵌套数组添加元素
原始数据
let data = [ { foo: true, bar: [ 1, 2, 3 ] }, { foo: true, bar: [ 8, 9 ] } ];
需求
需要使用扩展语法(...),向索引1处对象的嵌套bar数组中添加元素,最终结果应为:
[ { foo: true, bar: [ 1, 2, 3 ] }, { foo: true, bar: [ 8, 9, 'new-item' ] } ]
注:常规的data[1].bar.push(0)方法不适用,必须用扩展语法实现。
尝试过的错误方法
- 错误写法1:
data = [ ...data, {[1]: { ...data[1], bar: [ ...data[1].bar, 'new-item' ] } }]
问题:新增了一个键为1的对象,未修改原数组索引1的元素。
- 错误写法2:
data = [ ...data, Object.assign({}, data[1], { bar }})
问题:新增了数组索引,未修改目标元素。
正确解决方案
要实现嵌套数组的修改,需逐层使用扩展语法替换目标位置的元素:
方法一:数组切片+扩展
data = [ ...data.slice(0, 1), // 保留索引0的元素 { ...data[1], // 复制原索引1对象的所有属性 bar: [...data[1].bar, 'new-item'] // 扩展原bar数组并添加新元素 } ];
如果数组长度大于2,可添加...data.slice(2)保留后续元素。
方法二:Object.assign结合扩展
data = Object.assign([], data, { 1: { ...data[1], bar: [...data[1].bar, 'new-item'] } });
在线测试代码
let data = [ { foo: true, bar: [ 1, 2, 3 ] }, { foo: true, bar: [ 8, 9 ] } ]; // 正确的扩展语法实现 data = [ ...data.slice(0, 1), { ...data[1], bar: [...data[1].bar, 'new-item'] } ]; console.log(data);
内容的提问来源于stack exchange,提问作者0stone0
相关产品推荐
相关产品推荐

