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

JavaScript:更新深度嵌套对象数组中指定元素的children字段

实现嵌套数组元素的children更新函数

需求说明

给定一个嵌套层级不确定的数组,数组中每个元素的children字段可能为undefined,也可能是包含至少一个子元素的数组,且所有元素的key值都是唯一的。示例数组如下:

const arr = [{
    key: '001',
    children: [{
        key: 'abc',
        children: [{
            key: 'ee',
            children: [{
                key: 'goc',
            }, {
                key: 'zzv',
                children: [{
                    key: '241',
                }],
            }],
        }],
    }, {
        key: '125',
        children: undefined,
    }],
}, {
    key: '003',
    children: [{
        key: 'ahge',
    }, {
        key: '21521',
    }],
}];

我们需要编写一个函数,接收目标key、待更新的children数组,找到对应key的元素并更新它的children字段,最终返回完整的原数组。函数的基础框架如下:

// 返回已更新目标元素的数组的函数——如何实现?
const mysteryFn = (arr, key, childrenToUpdate) => {
 // 编写实现逻辑..

 return arr;
}


const key = 'goc';
const childrenToUpdate = [{
 key: '12345',
}, {
 key: '25221a',
}];

const newArr = mysteryFn(arr, key, childrenToUpdate);

预期结果

调用函数后,newArr应如下所示:

const newArr = [{
    key: '001',
    children: [{
        key: 'abc',
        children: [{
            key: 'ee',
            children: [{
                key: 'goc',
                children: [{
                    key: '12345',
                }, {
                    key: '25221a',
                }],
            }, {
                key: 'zzv',
                children: [{
                    key: '241',
                }],
            }],
        }],
    }, {
        key: '125',
        children: undefined,
    }],
}, {
    key: '003',
    children: [{
        key: 'ahge',
    }, {
        key: '21521',
    }],
}];

实现方案

可以用递归遍历的方式处理嵌套结构,因为层级未知,递归能自然覆盖所有深度:

const mysteryFn = (arr, key, childrenToUpdate) => {
  // 遍历当前层级的每个元素
  for (const item of arr) {
    if (item.key === key) {
      // 找到目标元素,更新children
      item.children = childrenToUpdate;
      return arr; // 找到后直接返回,因为key唯一
    }
    // 如果当前元素有children且不是undefined,递归遍历子数组
    if (item.children && Array.isArray(item.children)) {
      const result = mysteryFn(item.children, key, childrenToUpdate);
      // 如果子数组中找到并更新了,直接返回原数组
      if (result) return arr;
    }
  }
  // 没找到目标key,返回原数组
  return arr;
};

方案说明

  1. 遍历当前层级的元素,匹配到目标key就直接更新其children字段,因为所有key唯一,找到后立即返回原数组。
  2. 如果当前元素存在children且是数组,就递归遍历子数组,继续查找目标key。
  3. 若遍历完所有层级都没找到目标key,则直接返回原数组,不做任何修改。

这个方案逻辑清晰,能处理任意嵌套深度,且因为key唯一,找到目标后立即终止遍历,效率较高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 06:27:28