
本教程旨在指导开发者如何使用 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;
};代码解释:
立即学习“Java免费学习笔记(深入)”;
使用示例:
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);
本教程介绍了一种使用 JavaScript 从深度嵌套的分类数据中提取指定分类 ID 的所有子项并扁平化的方法。该方法使用栈数据结构和函数式编程技巧,避免使用 for、forEach 和 while 循环,提高了代码的可读性和可维护性。通过理解和应用本教程中的代码示例,您可以轻松地处理复杂的分类数据,并提取所需的信息。
以上就是从嵌套数据中提取指定分类 ID 的所有子项并扁平化:JavaScript 教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号