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

如何获取JavaScript数组中指定分类的所有直接/嵌套子分类

递归获取嵌套分类所有子项的正确实现

原代码的问题

你的递归函数失效主要有两个原因:

  1. 属性名拼写错误:数组中存储父级ID的键是parentCategoryId,但你在过滤时写了cat.parentCategory == category.id,导致无法匹配到任何子分类。
  2. 全局变量副作用:使用全局数组newCategoriesArray会导致多次调用时数据残留,结果不符合预期。

正确实现(基础版)

下面是修复后的纯函数代码,避免全局变量污染,支持任意深度的嵌套分类:

function getAllChildCategories(rootId, categories) {
  const result = [];

  // 递归遍历函数
  function traverse(category) {
    // 找到当前分类的直接子项
    const children = categories.filter(cat => cat.parentCategoryId === category.id);
    // 将子项加入结果数组
    result.push(...children);
    // 递归处理每个子项的子分类
    children.forEach(child => traverse(child));
  }

  // 定位根分类
  const rootCategory = categories.find(cat => cat.id === rootId);
  if (rootCategory) {
    traverse(rootCategory);
  }

  return result;
}

// 使用示例
const categories = [
    {id:1,name:'beauty',parentCategoryId:null},
    {id:2, name:'health', parentCategoryId:null},
    {id:3, name:'hair care', parentCategoryId:1},
    {id:4, name:'hair oil', parentCategoryId:3},
    {id:5, name:'kumarika hair oil', parentCategoryId:4},
    {id:6, name:'supplements', parentCategoryId:2}
];

// 获取beauty分类的所有子项
const beautySubCategories = getAllChildCategories(1, categories);
console.log(beautySubCategories);

执行后会输出你期望的结果:

[
    {id:3, name:'hair care', parentCategoryId:1},
    {id:4, name:'hair oil', parentCategoryId:3},
    {id:5, name:'kumarika hair oil', parentCategoryId:4},
]

性能优化版(适合大量分类场景)

如果分类数量较多,多次调用filter会导致性能损耗,可以预先构建父ID到子分类的映射,减少重复遍历:

function getAllChildCategories(rootId, categories) {
  // 构建ID到分类对象的映射
  const categoryMap = new Map(categories.map(cat => [cat.id, cat]));
  // 构建父ID到子分类数组的映射
  const parentChildrenMap = new Map();
  
  categories.forEach(cat => {
    if (cat.parentCategoryId !== null) {
      if (!parentChildrenMap.has(cat.parentCategoryId)) {
        parentChildrenMap.set(cat.parentCategoryId, []);
      }
      parentChildrenMap.get(cat.parentCategoryId).push(cat);
    }
  });

  const result = [];

  function traverse(categoryId) {
    const children = parentChildrenMap.get(categoryId) || [];
    result.push(...children);
    children.forEach(child => traverse(child.id));
  }

  if (categoryMap.has(rootId)) {
    traverse(rootId);
  }

  return result;
}

这个版本通过预构建映射,将时间复杂度从O(n²)降低到O(n),处理大量分类时性能更优。

内容的提问来源于stack exchange,提问作者kazi nur hossain tipu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 13:47:44