如何向JS多层嵌套数组的attrs对象添加isNegative属性?
给多层嵌套数组对象添加属性的解决方案
原始代码
const array = [{ id: 1, name: 'test', attrs: [{ name: 'Attribute 1', description: 'Description 1', }], values: [{ name: 'value 1', attrs: [{ name: 'Attribute 1', type: 'Type 1', }, { name: 'Attribute 2', type: 'Type 2', }, ], }, ], }, ]; const newArray = array.map((item) => { return { ...item, isNegative: true }; }); console.log(newArray);
需求说明
需要同时给以下两处的每个对象添加isNegative: true属性:
array[].attrs数组中的每个元素array[].values[].attrs数组中的每个元素
实现代码
通过嵌套map遍历层级结构,并用辅助函数复用属性添加逻辑,避免重复代码:
const array = [{ id: 1, name: 'test', attrs: [{ name: 'Attribute 1', description: 'Description 1', }], values: [{ name: 'value 1', attrs: [{ name: 'Attribute 1', type: 'Type 1', }, { name: 'Attribute 2', type: 'Type 2', }, ], }, ], }, ]; // 辅助函数:给传入的attrs数组每个对象添加isNegative属性 const addIsNegativeToAttrs = (attrs) => { return attrs.map(attr => ({ ...attr, isNegative: true })); }; const newArray = array.map(item => ({ ...item, // 处理当前item的attrs数组 attrs: addIsNegativeToAttrs(item.attrs), // 遍历values数组,处理每个value的attrs数组 values: item.values.map(value => ({ ...value, attrs: addIsNegativeToAttrs(value.attrs) })) })); console.log(newArray);
代码说明
- 辅助函数
addIsNegativeToAttrs负责接收attrs数组,返回添加了isNegative属性的新数组,避免重复编写map逻辑。 - 外层
array.map遍历每个顶层对象,展开原对象属性后,分别处理attrs和values:- 直接调用辅助函数处理当前对象的
attrs - 对
values数组再次使用map,遍历每个value对象,展开属性后调用辅助函数处理其attrs
- 直接调用辅助函数处理当前对象的
如果数据结构存在更深层次的嵌套(比如values里还有多层attrs),可以将逻辑改成递归函数,自动遍历所有包含attrs的层级。
内容的提问来源于stack exchange,提问作者Alien18
相关产品推荐
相关产品推荐

