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

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

DDD
发布: 2025-08-23 19:12:40
原创
395人浏览过

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

本文档提供了一个 JavaScript 教程,用于从深度嵌套的分类数据中提取特定分类 ID 的所有子项,并将结果扁平化为一个数组。该方法避免了使用 for、foreach 和 while 循环,而是采用栈结构和 map 等函数式编程技巧,提供了一种高效且可读性强的解决方案。同时,处理了未传递分类 ID 和传递的 ID 无子项等情况。

本文将介绍如何使用 JavaScript 从一个深度嵌套的分类数据结构中,根据给定的分类 ID 列表,提取这些 ID 对应的所有子项,并将结果扁平化为一个一维数组。我们将避免使用传统的 for、foreach 和 while 循环,而是采用更现代的函数式编程方法,提高代码的可读性和可维护性。

数据结构

首先,我们定义一个分类数据结构 Category,它包含 name、id、count 和 children 属性。children 属性是一个 Category 类型的数组,表示该分类的子分类。

interface Category {
  name: string;
  id: string;
  count: string;
  depth: string;
  children: Category[];
}
登录后复制

例如:

const data = [
    {
      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: []
        }
      ]
    }
  ];
登录后复制

实现方法

我们的目标是编写一个函数 getCategoriesChildren,它接收一个分类 ID 数组 categoryIds 和一个分类数据数组 categories 作为输入,并返回一个包含所有指定分类 ID 的子项的扁平化数组。

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

该函数的核心思路是使用栈来模拟深度优先搜索(DFS)。我们将初始的分类数据压入栈中,然后不断从栈中弹出元素,并检查该元素是否是目标分类的子项。如果是,则将其子项也压入栈中,继续搜索。

为了避免使用 for、foreach 和 while 循环,我们将使用 map 等函数式编程技巧来处理数组。

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;
};
登录后复制

代码解释:

  1. mapCategory 函数: 该函数用于从 Category 对象中提取 name、id 和 count 属性,创建一个新的对象。这是为了确保返回的子项数组只包含我们需要的属性。

  2. getCategoriesChildren 函数:

    • 参数: 接收一个分类 ID 数组 categoryIds 和一个分类数据数组 categories 作为输入。
    • foundChildren 数组: 用于存储找到的子项。
    • 处理 categoryIds 为空的情况: 如果 categoryIds 为空,则返回所有父分类和直接子分类。这里使用了 reduce 方法将 categories 数组转换为一个包含父分类和直接子分类的扁平化数组。
    • 初始化栈: 创建一个栈 stack,并将 categories 数组中的所有元素压入栈中。 每个元素除了 Category 属性外,还包含一个 isDesired 属性,用于标记该分类是否是目标分类的子项。
    • 循环处理栈中的元素:
      • 从栈中弹出一个元素 category。
      • 判断该元素是否是目标分类的子项:如果 categoryIds 包含该元素的 id,或者该元素的 isDesired 属性为 true,则认为该元素是目标分类的子项。
      • 如果该元素是目标分类的子项,则将其子项添加到 foundChildren 数组中。
      • 将该元素的子项压入栈中。如果该元素是目标分类的子项,则将其子项的 isDesired 属性设置为 true。
    • 返回结果: 返回 foundChildren 数组。

使用示例

const data = [
    {
      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: []
        }
      ]
    }
  ];

const categoryIds = ['22', '3'];
const children = getCategoriesChildren(categoryIds, data);
console.log(children);
// Expected Output:
// [
//   { name: 'Engine', id: '101', count: '1' },
//   { name: 'Engine and Brakes', id: '344', count: '1' },
//   { name: 'SpeedBike', id: '4', count: '12' }
// ]

const noCategoryIds = [];
const parentAndChildren = getCategoriesChildren(noCategoryIds, data);
console.log(parentAndChildren);
// Expected Output:
// [
//   { name: 'Car', id: '19', count: '20' },
//   { name: 'Wheel', id: '22', count: '3' },
//   { name: 'Bike', id: '3', count: '12' },
//   { name: 'SpeedBike', id: '4', count: '12' }
// ]

const emptyCategoryIds = ['999'];
const emptyChildren = getCategoriesChildren(emptyCategoryIds, data);
console.log(emptyChildren);
// Expected Output:
// []
登录后复制

总结

本文介绍了一种使用 JavaScript 从深度嵌套的分类数据结构中提取指定分类 ID 的所有子项,并将结果扁平化为一个数组的方法。该方法避免了使用传统的 for、foreach 和 while 循环,而是采用栈结构和 map 等函数式编程技巧,提供了一种高效且可读性强的解决方案。该方法可以应用于各种需要处理嵌套数据结构的场景,例如:网站导航、商品分类、组织结构等。

以上就是从嵌套数据中提取指定分类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号