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

使用 JavaScript 查找并扁平化特定分类 ID 的子项

DDD
发布: 2025-08-23 20:26:01
原创
443人浏览过

使用 javascript 查找并扁平化特定分类 id 的子项

本文档提供了一个 JavaScript教程,用于从嵌套的分类数据结构中提取特定分类ID的所有子项,并将结果扁平化为一个数组。它涵盖了处理不同场景的逻辑,包括指定分类ID和未指定分类ID的情况,并提供了可复用的代码示例。

场景描述

假设我们有一个嵌套的分类数据结构,每个分类都有 id、name、count 和 children 属性。children 属性是一个包含子分类的数组,子分类也具有相同的结构。我们的目标是编写一个 JavaScript 函数,该函数能够:

  1. 接收一个分类 ID 数组作为输入。
  2. 如果提供了分类 ID 数组,则返回所有指定分类 ID 的子项,并将结果扁平化为一个数组。
  3. 如果没有提供分类 ID 数组,则返回所有顶级分类及其直接子项。
  4. 如果提供的分类 ID 没有子项,则返回一个空数组。
  5. 避免使用 for、foreach 和 while 循环。

实现方法

我们可以使用递归和栈数据结构来实现这个功能,同时避免使用 for、foreach 和 while 循环。

代码示例(TypeScript)

博特妙笔
博特妙笔

公职人员公文写作平台,集查、写、审、学为一体。

博特妙笔 18
查看详情 博特妙笔

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

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

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;
};

// 示例数据
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: []
        }
      ]
    }
  ];

// 示例用法
const categoryIds = ['22', '3'];
const children = getCategoriesChildren(categoryIds, data);
console.log(children);

const noCategoryIds = [];
const defaultChildren = getCategoriesChildren(noCategoryIds, data);
console.log(defaultChildren);
登录后复制

代码解释:

  1. Category 接口: 定义了分类对象的结构。
  2. mapCategory 函数: 用于从 Category 对象中提取 id、count 和 name 属性,创建一个新的对象。
  3. getCategoriesChildren 函数:
    • 接收一个分类 ID 数组 categoryIds 和一个分类数组 categories 作为输入。
    • 如果 categoryIds 为空,则返回所有顶级分类及其直接子项。
    • 如果 categoryIds 不为空,则使用栈数据结构来遍历分类树,找到所有指定分类 ID 的子项。
    • stack 存储 categories 与附加的 isDesired?: boolean 属性,用于指示该 category 是否为指定 ID 的子代。
    • 如果 category 的 id 在 categoryIds 中,则将其 children 压入栈中,并设置 isDesired: true。
    • 当 category id 在 categoryIds 中或 category.isDesired 为 true 时,才将其 children 加入 foundChildren。
  4. 示例数据和用法: 展示了如何使用 getCategoriesChildren 函数。

注意事项

  • 此方法使用栈数据结构进行深度优先搜索,适用于深度嵌套的分类数据。
  • 代码使用 TypeScript 编写,可以轻松转换为 JavaScript。
  • mapCategory 函数用于提取必要的属性,可以根据实际需求进行修改。
  • 可以根据需要修改代码以处理其他场景,例如处理循环引用或限制搜索深度。

总结

本文提供了一个使用 JavaScript 查找并扁平化特定分类 ID 的子项的教程。通过使用栈数据结构和递归,我们可以避免使用 for、foreach 和 while 循环,从而使代码更加简洁和易于理解。 此方法适用于处理深度嵌套的分类数据,并且可以根据实际需求进行修改。

以上就是使用 JavaScript 查找并扁平化特定分类 ID 的子项的详细内容,更多请关注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号