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

如何修改嵌套对象数组中指定对象的属性值

嵌套对象数组的属性修改方案

你的代码存在几个关键问题,导致无法正常运行:

  • 直接链式访问item.things.food.fruit会触发报错:部分数组项是空对象(无things属性),且things是数组而非对象,无法直接读取food属性;
  • map回调仅返回修改后的fruit值,最终newArray会丢失原数组结构,变成仅包含修改值或undefined的数组。

以下是两种可行的实现方式:

方式一:Immutable操作(不修改原数据)

这种方式通过生成新数组/新对象完成修改,保留原数据完整性:

const array = [
  {
    things: [
      { car: 'ford' },
      { colour: 'red' },
      {
        food: [
          { veg: 'beans' },
          { fruit: 'plum' },
        ],
      },
    ],
  },
  {},
  {},
]

const newArray = array.map(item => {
  if (!item.things) return item;

  const updatedThings = item.things.map(thing => {
    if (!thing.food) return thing;

    const updatedFood = thing.food.map(foodItem => {
      if (foodItem.fruit === 'plum') {
        return { ...foodItem, fruit: 'strawberry' };
      }
      return foodItem;
    });

    return { ...thing, food: updatedFood };
  });

  return { ...item, things: updatedThings };
});
  • 逐层判断属性是否存在,避免运行时错误;
  • 用map生成新数组,结合对象展开运算符...创建新对象,确保原数据不被篡改;
  • 仅对匹配fruit: 'plum'的项生成修改后的新对象,其余项保持原样。

方式二:直接修改原数组

如果不需要保留原数据,可以用forEach遍历修改:

const array = [
  {
    things: [
      { car: 'ford' },
      { colour: 'red' },
      {
        food: [
          { veg: 'beans' },
          { fruit: 'plum' },
        ],
      },
    ],
  },
  {},
  {},
]

array.forEach(item => {
  if (!item.things) return;
  item.things.forEach(thing => {
    if (!thing.food) return;
    thing.food.forEach(foodItem => {
      if (foodItem.fruit === 'plum') {
        foodItem.fruit = 'strawberry';
      }
    });
  });
});
  • 逐层遍历嵌套结构,找到目标属性直接修改;
  • 代码更简洁,但会改变原数组内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:25:30