
本文档提供了一个 JavaScript教程,用于从嵌套的分类数据结构中提取特定分类ID的所有子项,并将结果扁平化为一个数组。它涵盖了处理不同场景的逻辑,包括指定分类ID和未指定分类ID的情况,并提供了可复用的代码示例。
假设我们有一个嵌套的分类数据结构,每个分类都有 id、name、count 和 children 属性。children 属性是一个包含子分类的数组,子分类也具有相同的结构。我们的目标是编写一个 JavaScript 函数,该函数能够:
我们可以使用递归和栈数据结构来实现这个功能,同时避免使用 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);代码解释:
本文提供了一个使用 JavaScript 查找并扁平化特定分类 ID 的子项的教程。通过使用栈数据结构和递归,我们可以避免使用 for、foreach 和 while 循环,从而使代码更加简洁和易于理解。 此方法适用于处理深度嵌套的分类数据,并且可以根据实际需求进行修改。
以上就是使用 JavaScript 查找并扁平化特定分类 ID 的子项的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号