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

如何在reduce扁平化数组后修改原数组中指定ID的对象?

通过ID修改嵌套数组中对象的属性

要直接修改原嵌套数组中对应ID的对象属性,最简洁的方式是递归遍历原数组,找到目标ID的对象后直接修改其test属性,找到后可提前终止遍历以提升效率:

function updateTestById(items, targetId) {
  for (const item of items) {
    // 找到目标对象,修改属性并返回true表示已找到
    if (item.id === targetId) {
      item.test = true;
      return true;
    }
    // 递归遍历子数组,若找到则终止后续遍历
    if (item.items?.length) {
      const found = updateTestById(item.items, targetId);
      if (found) return true;
    }
  }
  // 未找到目标ID时返回false
  return false;
}

// 使用示例:修改id为10的对象test属性
updateTestById(items, 10);

为什么这是最优解

  • 直接操作原数组,无需依赖扁平化后的数组,避免不必要的关联处理
  • 递归逻辑贴合数组的嵌套结构,代码简洁易读
  • 找到目标后立即终止遍历,不会做多余的循环,性能高效

如果需要支持批量修改多个ID,只需稍作调整:

function updateTestByIds(items, targetIds) {
  const idSet = new Set(targetIds);
  for (const item of items) {
    if (idSet.has(item.id)) {
      item.test = true;
      idSet.delete(item.id);
      if (idSet.size === 0) return true; // 全部找到就终止
    }
    if (item.items?.length) {
      const foundAll = updateTestByIds(item.items, [...idSet]);
      if (foundAll) return true;
    }
  }
  return idSet.size === 0;
}

// 使用示例:修改id为4和10的对象test属性
updateTestByIds(items, [4, 10]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 01:57:26