在JavaScript中为数组指定索引的对象添加数组的方法
实现方法
方法一:直接修改原数组
如果不需要保留原数组的原始状态,可以直接通过数组索引定位目标对象,为其添加newArr属性:
// 原始数组 const arr = [ {name:{"id": 1},data:{"dataVal": 'value1'}}, {name:{"id": 2},data:{"dataVal": 'value2'}}, {name:{"id": 3},data:{"dataVal": 'value3'}} ]; // 指定要添加属性的目标索引 const targetIndex = 0; // 为目标对象添加空数组属性 arr[targetIndex].newArr = [];
执行后原数组就会变成你预期的结构。
方法二:生成新数组(不修改原数组)
如果需要保留原数组的原始数据,可以使用map方法创建新数组,仅对目标索引的对象进行修改:
// 原始数组 const arr = [ {name:{"id": 1},data:{"dataVal": 'value1'}}, {name:{"id": 2},data:{"dataVal": 'value2'}}, {name:{"id": 3},data:{"dataVal": 'value3'}} ]; const targetIndex = 0; // 生成新数组,仅目标索引的对象添加newArr属性 const updatedArr = arr.map((item, index) => index === targetIndex ? {...item, newArr: []} : item );
这种方式下原数组不会被改动,updatedArr就是你需要的新数组。
额外提示
如果不确定目标索引是否在数组有效范围内,可以添加范围判断避免报错:
const targetIndex = 0; if (targetIndex >= 0 && targetIndex < arr.length) { // 执行上述添加属性的操作 } else { console.log('指定索引超出数组范围'); }
内容的提问来源于stack exchange,提问作者React_Coder
相关产品推荐
相关产品推荐

