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

如何将含嵌套children的对象数组转换为带层级的一维数组

将嵌套层级数组扁平化为带层级的一维数组

可以用递归方式实现需求,核心思路是遍历每个节点并记录当前层级,再递归处理子节点并累加层级:

function flattenTree(arr, level = 0) {
  let result = [];
  arr.forEach(item => {
    // 提取当前节点的id、title和对应层级
    result.push({ id: item.id, title: item.title, level });
    // 递归处理子节点,层级+1
    if (item.children?.length) {
      result = result.concat(flattenTree(item.children, level + 1));
    }
  });
  return result;
}

// 测试使用
let a = [
    { id: 0, title: 'a', children: [ { id: 1, title: 'aa', children: [ { id: 2, title: 'aaa', children: []} ]}] },
    { id: 3, title: 'b', children: [ { id: 4, title: 'bb', children: []}] },
    { id: 5, title: 'c', children: [] },
    { id: 6, title: 'd', children: [ { id: 7, title: 'dd', children: [ { id: 8, title: 'ddd', children: []} ]}] },
];

let b = flattenTree(a);
console.log(b);

代码说明

  • 函数接收两个参数:待处理的数组arr,以及当前节点的层级level(默认值为0,对应最顶层节点)。
  • 遍历数组中的每个节点,先将节点的id、title和当前level存入结果数组。
  • 检查当前节点是否有非空的children数组,若有则递归调用函数处理子节点,同时将层级加1,最后把递归返回的子节点结果合并到主结果数组中。
  • 递归会自动适配任意深度的嵌套层级,不管嵌套多少层都能正确遍历所有节点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 09:15:48