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

如何基于层级数组对象的selected属性生成路径数组

问题分析

你的需求是根据层级数组中节点的selected属性生成斜杠分隔的索引路径数组,三个场景规则如下:

  • 场景1(selected=none):不存储任何路径
  • 场景2(selected=partial):不存储当前节点路径,但需递归存储子节点中selected=all的所有路径
  • 场景3(selected=all):存储当前节点路径,且递归存储所有子节点的路径

当前代码存在以下问题:

  1. 全局变量path被复用,导致路径拼接混乱,比如处理完0/0的子节点后,path残留为0/0/1,后续处理0/1时会基于错误路径拼接
  2. 对selected=all的节点未递归处理其子节点,仅添加了当前节点的直接子节点路径,遗漏了更深层级的子节点
  3. 错误将selected=partial的节点路径(如1、1/0)加入结果数组,违反场景2规则
  4. 递归调用时路径参数传递错误,导致子节点路径生成异常
修复后的代码
const treeData = [{
    name: 'Infiniti',
    selected: 'all',
    children: [{
        name: 'G50',
        selected: 'all',
        children: [{
            name: 'Pure AWD',
            selected: 'all',
          },
          {
            name: 'Luxe',
            selected: 'all',
          },
        ],
      },
      {
        name: 'QX50',
        selected: 'all',
        children: [{
            name: 'Pure AWD',
            selected: 'all',
          },
          {
            name: 'Luxe',
            selected: 'all',
          },
        ],
      },
    ],
  },
  {
    name: 'BMW',
    selected: 'partial',
    children: [{
        name: '2 Series',
        selected: 'partial',
        children: [{
            name: 'Coupé',
            selected: 'all',
          },
          {
            name: 'Gran Coupé',
            selected: 'none',
          },
        ],
      },
      {
        name: '3 Series',
        selected: 'none',
        children: [{
            name: 'Sedan',
            selected: 'none',
          },
          {
            name: 'PHEV',
            selected: 'none',
          },
        ],
      },
    ],
  },
];

function getIndexPaths(tree) {
  const result = [];
  
  function traverse(nodes, parentPath = '') {
    nodes.forEach((node, index) => {
      const currentPath = parentPath ? `${parentPath}/${index}` : `${index}`;
      
      switch (node.selected) {
        case 'all':
          // 场景3:添加当前路径,递归处理所有子节点
          result.push(currentPath);
          if (node.children?.length) {
            traverse(node.children, currentPath);
          }
          break;
        case 'partial':
          // 场景2:不添加当前路径,仅递归处理子节点寻找all节点
          if (node.children?.length) {
            traverse(node.children, currentPath);
          }
          break;
        case 'none':
          // 场景1:跳过所有处理
          break;
      }
    });
  }
  
  traverse(tree);
  return result;
}

console.log(getIndexPaths(treeData));
// 输出:["0", "0/0", "0/0/0", "0/0/1", "0/1", "0/1/0", "0/1/1", "1/0/0"]
代码说明
  1. 使用**局部递归函数traverse**替代全局变量,通过参数传递当前父路径,避免路径污染
  2. 针对不同selected值分支处理:
    • all:先将当前路径加入结果数组,再递归遍历所有子节点,确保所有层级的子节点路径都被添加
    • partial:不添加当前路径,直接递归遍历子节点,仅收集子节点中all的路径
    • none:直接跳过,不做任何处理
  3. 使用可选链操作符?.处理子节点为空的情况,避免报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:35:20