
本文介绍了在 JavaScript 中处理深度嵌套数组,并根据指定的 ID 列表提取子元素的方法。通过迭代方式,避免了递归可能导致的栈溢出问题,并提供了清晰的代码示例和使用说明,帮助开发者高效地处理复杂的数据结构。无论是否提供 ID 列表,都能返回期望的子元素数组。
在 JavaScript 开发中,经常会遇到需要处理嵌套较深的数组结构的情况。例如,树形结构的组织数据,每个节点可能包含子节点,而子节点又可能包含更深层次的子节点。本文将介绍一种高效的方法,用于从这种嵌套数组中,根据给定的 ID 列表,提取特定节点的直接子节点。
核心思路是采用迭代的方式遍历嵌套数组,避免使用递归,从而避免了潜在的栈溢出风险,尤其是在处理深度非常大的嵌套结构时。
判断是否提供了 ID 列表:
立即学习“Java免费学习笔记(深入)”;
提取特定子节点(当提供了 ID 列表时):
提取顶层节点及其子节点(当没有提供 ID 列表时):
type Category = {
name: string;
id: string;
count: string;
depth: string;
children: Category[];
};
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 = [
{
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);
// Expected Output:
// [
// { name: 'Engine and Brakes', id: '344', count: '1' },
// { name: 'SpeedBike', id: '4', count: '12' }
// ]
// 获取所有顶层节点及其子节点
const children2 = getCategoriesChildren([], data);
console.log(children2);
// 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' }
// ]本文介绍了一种高效的方法,用于从 JavaScript 的深度嵌套数组中,根据给定的 ID 列表,提取特定节点的直接子节点。该方法使用迭代方式,避免了递归可能导致的栈溢出问题,并提供了清晰的代码示例和使用说明。通过学习本文,可以更好地处理复杂的数据结构,提高开发效率。
以上就是JavaScript 中获取嵌套数组的子元素的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号