
本文旨在提供一种高效且避免使用 for、foreach 和 while 循环的方法,从深度嵌套的 JavaScript 数组中提取特定 ID 的直接子元素。通过迭代方法,我们能够根据传入的 ID 数组,返回相应的子元素,或者在未传入 ID 时,返回顶层元素的直接子元素。同时,本文还提供了 TypeScript 类型定义,以增强代码的可读性和可维护性。
在处理具有多层嵌套结构的数据时,提取特定层级的子元素是一个常见的需求。传统的循环方式虽然可以实现,但在处理深度嵌套的数据时,代码可读性和效率都会受到影响。本文介绍一种使用迭代方法,结合栈数据结构,从深度嵌套的数组中提取特定 ID 的直接子元素,并避免使用传统的 for、foreach 和 while 循环。
该算法的核心思想是使用栈来模拟深度优先搜索(DFS)的过程,从而遍历整个嵌套数组。
首先,定义 Category 的 TypeScript 类型,增强代码可读性和可维护性。
立即学习“Java免费学习笔记(深入)”;
type Category = {
name: string;
id: string;
count: string;
depth: string;
children: Category[];
};接下来是核心函数 getCategoriesChildren 的实现:
const getCategoriesChildren = (
categoryIds: Category['id'][],
categories: Category[],
): Pick<Category, 'id' | 'count' | 'name'>[] => {
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 = [...categories];
while (stack.length) {
const category = stack.pop();
if (!category) continue;
if (categoryIds.includes(category.id)) {
foundChildren.push(
...category.children.map((childCategory) => ({
name: childCategory.name,
id: childCategory.id,
count: childCategory.count,
})),
);
}
stack.push(...category.children);
}
return foundChildren;
};
const mapCategory = (category: Category): Pick<Category, 'id' | 'count' | 'name'> => ({
name: category.name,
id: category.id,
count: category.count,
});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: []
}
]
}
];
// 获取 id 为 '101' 和 '3' 的元素的直接子元素
const children1 = getCategoriesChildren(['101', '3'], data);
console.log(children1);
// 输出:
// [
// { name: 'Engine and Brakes', id: '344', count: '1' },
// { name: 'SpeedBike', id: '4', count: '12' }
// ]
// 获取顶层元素及其直接子元素
const children2 = getCategoriesChildren([], data);
console.log(children2);
// 输出:
// [
// { name: 'Car', id: '19', count: '20' },
// { name: 'Wheel', id: '22', count: '3' },
// { name: 'Bike', id: '3', count: '12' },
// { name: 'SpeedBike', id: '4', count: '12' }
// ]本文介绍了一种使用迭代方法从深度嵌套的 JavaScript 数组中提取特定 ID 的直接子元素的方案。该方案避免了传统的循环,提高了代码的可读性和可维护性。同时,使用 TypeScript 类型定义可以增强代码的类型安全。在实际应用中,需要根据具体的数据结构和性能要求选择合适的算法。
以上就是JavaScript 中获取深度嵌套数组的子元素的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号