You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向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);

代码说明

  1. 辅助函数addIsNegativeToAttrs负责接收attrs数组,返回添加了isNegative属性的新数组,避免重复编写map逻辑。
  2. 外层array.map遍历每个顶层对象,展开原对象属性后,分别处理attrs和values:
    • 直接调用辅助函数处理当前对象的attrs
    • 对values数组再次使用map,遍历每个value对象,展开属性后调用辅助函数处理其attrs

如果数据结构存在更深层次的嵌套(比如values里还有多层attrs),可以将逻辑改成递归函数,自动遍历所有包含attrs的层级。

内容的提问来源于stack exchange,提问作者Alien18

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 16:31:16