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

Angular 10中如何递归生成嵌套分类数组

分类树递归嵌套实现方案

核心逻辑

递归遍历的终止&执行规则:

  • 遍历每个节点时,先以节点的categoryCode为key去categoryData中查找对应配置
  • 如果找不到对应配置,或者对应配置的children为空数组,当前分支递归终止
  • 如果存在有效子节点配置,将子节点列表赋值给当前节点的children属性,再逐个对子节点执行相同的遍历逻辑

实现代码

function fillCategoryTree(treeNodes, categoryMap) {
  treeNodes.forEach(node => {
    const currentMapItem = categoryMap[node.categoryCode];
    if (currentMapItem?.children?.length) {
      node.children = currentMapItem.children;
      fillCategoryTree(node.children, categoryMap);
    }
  });
  return treeNodes;
}

// 调用方式
const categoriesData = [{"categoryCode":"cat1","name":"Procurement","parentCategoryCode":"ROOT_NODE","active":true,"archive":false,"children":[]}];
const categoryData = {"8596":{"operation":true,"children":[]},"9890":{"operation":true,"children":[{"categoryCode":"8596","name":"Sub-Sub-Sub-Procurement","parentCategoryCode":"9890","active":true,"archive":false}]},"125240":{"operation":true,"children":[{"categoryCode":"9890","name":"Syb-Sub-Procurement","parentCategoryCode":"125240","active":true,"archive":false}]},"dvs":{"operation":true,"children":[]},"cat1":{"operation":true,"children":[{"categoryCode":"125240","name":"Procurement-Sub","parentCategoryCode":"cat1","active":true,"archive":false}]}};

const finalCategoryTree = fillCategoryTree(categoriesData, categoryData);

执行结果

执行后生成的完整嵌套结构层级如下:

  • cat1(Procurement)
    • children: 125240(Procurement-Sub)
      • children: 9890(Syb-Sub-Procurement)
        • children: 8596(Sub-Sub-Sub-Procurement)
          • children: 空数组,当前分支递归终止

注意事项

  • 上述实现会直接修改传入的原categoriesData对象,如果需要保留原数据,传入前先对categoriesData做深拷贝即可
  • 代码做了空值容错,即使某个节点的code在categoryData中不存在,也不会抛出异常,会直接终止对应分支的遍历

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 04:24:23