
本文档提供了一个 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;
};代码解释:
mapCategory 函数: 该函数用于从 Category 对象中提取 name、id 和 count 属性,创建一个新的对象。这是为了确保返回的子项数组只包含我们需要的属性。
getCategoriesChildren 函数:
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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号