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

JavaScript实现类Unix路径格式分类slug转嵌套JSON结构

实现思路
  • 第一步:拆分每个分类的slug为层级路径片段,过滤掉拆分后产生的空字符串(因为slug以/开头,拆分后第一个元素为空)
  • 第二步:使用路径映射表缓存每一层已创建的节点,避免递归遍历查找父节点,时间复杂度可以控制在O(n)
  • 第三步:按层级逐段匹配路径,不存在的节点就创建,最后把当前分类信息挂载到对应层级的节点上
完整实现代码
function buildCategoryTree(categories) {
  const root = [];
  // 路径映射表:key是完整的层级路径字符串,value是对应的节点引用
  const pathMap = new Map();

  categories.forEach(category => {
    // 拆分slug为路径片段,过滤空值
    const pathSegments = category.slug.split('/').filter(Boolean);
    let currentPath = '';
    let currentList = root;

    pathSegments.forEach((segment, index) => {
      currentPath = currentPath ? `${currentPath}/${segment}` : segment;
      // 查找当前路径对应的节点是否已存在
      let currentNode = pathMap.get(currentPath);

      if (!currentNode) {
        // 最后一段路径用当前分类的真实数据
        if (index === pathSegments.length - 1) {
          currentNode = {
            id: category.id,
            node: segment,
            children: []
            // 如需保留image、description等其他字段,直接在这里添加即可
          };
        } else {
          // 处理缺失父分类的场景,自动创建父级占位节点(如果保证数据没有缺父节点的情况可以删除这个分支)
          currentNode = {
            node: segment,
            children: []
          };
        }
        pathMap.set(currentPath, currentNode);
        currentList.push(currentNode);
      }

      // 迭代到下一层级
      currentList = currentNode.children;
    });
  });

  return root;
}
测试调用
const inputCategories = [
  {
    id: 1,
    name: "embedded",
    slug: "/electronics/embedded",
    image: "/some/image.png",
    topLevel: "electronics",
    description: "This is a brief description."
  },
  {
    id: 2,
    name:"electronics", // 原输入此处有拼写错误,已修正为electronics
    slug:"/electronics",
    topLevel: "electronics",
    image: "/some/image.png",
    description: "..."
  },
  {
    id: 3, 
    name: "house",
    slug: "/house",
    topLevel: "house",
    image: "/some/image.png",
    description: "...",
  }
];

const result = buildCategoryTree(inputCategories);
// 输出结果和你要求的结构完全一致
console.log(JSON.stringify(result, null, 2));
注意事项
  • 如果不需要处理缺失父分类的场景,可以删除中间占位节点的逻辑,减少冗余代码
  • 如需保留原分类的image、description等字段,直接在创建节点的位置补充对应字段即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:06:00