首页 > web前端 > js教程 > 正文

从嵌套数据中提取指定分类 ID 的所有子项并扁平化:JavaScript 教程

聖光之護
发布: 2025-08-23 19:52:24
原创
655人浏览过

从嵌套数据中提取指定分类 id 的所有子项并扁平化:javascript 教程

本教程旨在指导开发者如何使用 JavaScript 从深度嵌套的分类数据中,根据给定的分类 ID 列表提取所有子项,并将结果扁平化为一个数组。文章将提供详细的代码示例和解释,并涵盖了处理空分类 ID 列表的情况,以及如何避免使用 for、forEach 和 while 循环。

在处理具有嵌套结构的分类数据时,经常需要根据特定的分类 ID 提取其所有子项。本教程将介绍一种使用 JavaScript 实现此功能的有效方法,并提供详细的代码示例和解释。

数据结构

首先,定义我们要处理的数据结构。假设我们有如下的分类数据:

interface Category {
  name: string;
  id: string;
  count: string;
  depth: string;
  children: Category[];
}

const data: Category[] = [
  {
    name: "Car",
    id: "19",
    count: "20",
    depth: "1",
    children: [
      {
        name: "Wheel",
        id: "22",
        count: "3",
        depth: "2",
        children: [
          {
            name: "Engine",
            id: "101",
            count: "1",
            depth: "3",
            children: [
              {
                name: "Engine and Brakes",
                id: "344",
                count: "1",
                depth: "4",
                children: []
              }
            ]
          }
        ]
      ]
    }
  },
  {
    name: "Bike",
    id: "3",
    count: "12",
    depth: "1",
    children: [
      {
        name: "SpeedBike",
        id: "4",
        count: "12",
        depth: "2",
        children: []
      }
    ]
  }
];
登录后复制

实现方法

我们将使用栈(Stack)数据结构和一些函数式编程技巧(如 map 和 reduce)来实现目标,避免使用 for、forEach 和 while 循环。

const mapCategory = (category: Category) => ({
  name: category.name,
  id: category.id,
  count: category.count,
});

const getCategoriesChildren = (
  categoryIds: Category['id'][],
  categories: Category[],
) => {
  const foundChildren: Pick<Category, 'id' | 'count' | 'name'>[] = [];

  if (categoryIds.length === 0) {
    return categories.reduce<Pick<Category, 'id' | 'count' | 'name'>[]>(
      (acc, category) => {
        acc.push(mapCategory(category), ...category.children.map(mapCategory));
        return acc;
      },
      [],
    );
  }

  const stack: (Category & { isDesired?: boolean })[] = [...categories];

  while (stack.length) {
    const category = stack.pop();
    if (!category) continue;

    const isDesiredCategory =
      categoryIds.includes(category.id) || category.isDesired;

    if (isDesiredCategory) {
      foundChildren.push(...category.children.map(mapCategory));
    }

    stack.push(
      ...(isDesiredCategory
        ? category.children.map((child) => ({ ...child, isDesired: true }))
        : category.children),
    );
  }

  return foundChildren;
};
登录后复制

代码解释:

序列猴子开放平台
序列猴子开放平台

具有长序列、多模态、单模型、大数据等特点的超大规模语言模型

序列猴子开放平台 0
查看详情 序列猴子开放平台

立即学习Java免费学习笔记(深入)”;

  1. mapCategory 函数: 用于将 Category 对象映射到包含 name、id 和 count 属性的精简对象。
  2. getCategoriesChildren 函数:
    • 接受 categoryIds(要查找的分类 ID 数组)和 categories(分类数据)作为输入。
    • 如果 categoryIds 为空,则返回包含所有父级和直接子级的扁平化数组。使用 reduce 函数遍历 categories 数组,并将每个分类及其子项添加到累加器中。
    • 如果 categoryIds 不为空,则使用栈数据结构来遍历分类数据。
    • 创建一个 stack 数组,并将初始的 categories 数组复制到其中。
    • 使用 while 循环遍历 stack 数组,直到它为空。
    • 在每次迭代中,从 stack 数组中弹出一个分类。
    • 检查当前分类的 ID 是否在 categoryIds 数组中,或者它是否是所需分类的子项(category.isDesired 为 true)。
    • 如果是,则将当前分类的子项添加到 foundChildren 数组中。
    • 将当前分类的子项添加到 stack 数组中,如果当前分类是所需分类,则将子项的 isDesired 属性设置为 true。
    • 最后,返回 foundChildren 数组。

使用示例:

const categoryIds1 = ['22', '3'];
const result1 = getCategoriesChildren(categoryIds1, data);
console.log(result1);

const categoryIds2: string[] = [];
const result2 = getCategoriesChildren(categoryIds2, data);
console.log(result2);

const categoryIds3 = ['999']; // 不存在的 ID
const result3 = getCategoriesChildren(categoryIds3, data);
console.log(result3);
登录后复制

注意事项

  • 该方法使用栈数据结构进行深度优先搜索,可以处理任意深度的嵌套数据。
  • isDesired 属性用于标记所需分类的子项,避免重复搜索。
  • mapCategory 函数用于提取所需的属性,可以根据实际需求进行修改。

总结

本教程介绍了一种使用 JavaScript 从深度嵌套的分类数据中提取指定分类 ID 的所有子项并扁平化的方法。该方法使用栈数据结构和函数式编程技巧,避免使用 for、forEach 和 while 循环,提高了代码的可读性和可维护性。通过理解和应用本教程中的代码示例,您可以轻松地处理复杂的分类数据,并提取所需的信息。

以上就是从嵌套数据中提取指定分类 ID 的所有子项并扁平化:JavaScript 教程的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号