
本文介绍了在 JavaScript 中,如何从深度嵌套的数组结构中,根据指定的 ID 获取子元素。通过迭代方法,避免了递归可能带来的栈溢出问题,并提供了详细的代码示例和类型定义,帮助开发者高效地处理复杂的数据结构。针对不同场景,包括指定 ID 和未指定 ID 的情况,给出了相应的解决方案。
在处理具有嵌套结构的 JSON 数据时,经常需要根据某些条件提取特定的子元素。例如,一个表示商品分类的数据结构可能包含多层嵌套的子分类。本文将介绍如何使用 JavaScript 从这种深度嵌套的数组中,根据给定的分类 ID 列表,提取这些 ID 对应的直接子元素。同时,我们还将讨论在没有指定 ID 的情况下,如何返回默认的父子元素列表。
核心问题在于如何有效地遍历深度嵌套的数组,并在遍历过程中根据条件筛选出符合要求的元素。传统的递归方法虽然直观,但在数据层级过深时可能会导致调用栈溢出。因此,我们将采用迭代的方式,结合栈的数据结构来解决这个问题。
以下是一种使用迭代和栈来实现该功能的 JavaScript 函数。该函数接受一个分类 ID 数组和一个包含嵌套分类数据的数组作为输入。
立即学习“Java免费学习笔记(深入)”;
type Category = {
name: string;
id: string;
count: string;
depth: string;
children: Category[];
};
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 = [...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' 的分类的直接子分类
console.log(getCategoriesChildren(['101', '3'], data));
// 输出:
// [
// { name: 'Engine and Brakes', id: '344', count: '1' },
// { name: 'SpeedBike', id: '4', count: '12' }
// ]
// 获取所有顶层分类及其直接子分类
console.log(getCategoriesChildren([], data));
// 输出:
// [
// { 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 深度嵌套数组子元素的获取方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号