值得一看
广告
彩虹云商城
广告

热门广告位

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

使用 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)

立即学习“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 循环,从而使代码更加简洁和易于理解。 此方法适用于处理深度嵌套的分类数据,并且可以根据实际需求进行修改。

温馨提示: 本文最后更新于2025-08-23 22:40:16,某些文章具有时效性,若有错误或已失效,请在下方留言或联系在线客服
文章版权声明 1 本网站名称: 创客网
2 本站永久网址:https://new.ie310.com
1 本文采用非商业性使用-相同方式共享 4.0 国际许可协议[CC BY-NC-SA]进行授权
2 本站所有内容仅供参考,分享出来是为了可以给大家提供新的思路。
3 互联网转载资源会有一些其他联系方式,请大家不要盲目相信,被骗本站概不负责!
4 本网站只做项目揭秘,无法一对一教学指导,每篇文章内都含项目全套的教程讲解,请仔细阅读。
5 本站分享的所有平台仅供展示,本站不对平台真实性负责,站长建议大家自己根据项目关键词自己选择平台。
6 因为文章发布时间和您阅读文章时间存在时间差,所以有些项目红利期可能已经过了,能不能赚钱需要自己判断。
7 本网站仅做资源分享,不做任何收益保障,创业公司上收费几百上千的项目我免费分享出来的,希望大家可以认真学习。
8 本站所有资料均来自互联网公开分享,并不代表本站立场,如不慎侵犯到您的版权利益,请联系79283999@qq.com删除。

本站资料仅供学习交流使用请勿商业运营,严禁从事违法,侵权等任何非法活动,否则后果自负!
THE END
喜欢就支持一下吧
点赞6赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容