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

如何遍历嵌套对象数组并更新子项属性(JS/Lodash实现)

解决方案

一、直接修改原对象(原地修改)

JS中对象是引用类型,直接修改itemsOfInterest里的子项,改动会自动反映到原对象上,不需要重新赋值数组。用Lodash或原生JS都能实现:

Lodash 写法

_.forEach(objects, (obj) => {
  _.forEach(obj.itemsOfInterest, (item) => {
    // 给子项添加新字段,直接修改原引用
    item.newProperty = true;
    // 若需逻辑处理,可根据item属性计算值:
    // item.newProperty = item.someKey === 'target' ? true : false;
  });
});

原生JS 写法

objects.forEach(obj => {
  obj.itemsOfInterest.forEach(item => {
    item.newProperty = true;
  });
});

你的原代码问题在于:外层_.map返回了新数组但未接收,且内层用_.map生成新数组后重新赋值给obj.itemsOfInterest属于多此一举——因为引用类型的特性,你已经直接修改了原数组里的子项,原obj.itemsOfInterest的子项状态已经更新。


二、不修改原对象,返回新结构(纯函数写法)

如果需要保留原数据,可通过深拷贝或逐层返回新对象实现:

Lodash 深拷贝后修改

// 深拷贝原数组,避免改动原数据
const newObjects = _.cloneDeep(objects);
_.forEach(newObjects, (obj) => {
  _.forEach(obj.itemsOfInterest, (item) => {
    item.newProperty = true;
  });
});

Lodash 链式map生成新结构

const newObjects = _.map(objects, (obj) => {
  // 返回新对象,保留原属性并替换itemsOfInterest
  return {
    ...obj,
    itemsOfInterest: _.map(obj.itemsOfInterest, (item) => {
      // 返回新的子项对象,不修改原item
      return {
        ...item,
        newProperty: true
      };
    })
  };
});

这种写法完全不触动原数据,返回一个与原结构一致的新数组,适合需要保留原始数据的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 15:48:30