数据源:
const items = [
{
id: 1,
name: "item1",
children: [
{
id: 11,
name: "item11",
children: [
{id: 111, name: "item111"},
{id: 112, name: "item112"}
]
},
{
id: 12,
name: "item12",
children: [
{id: 121, name: "item121"},
{id: 122, name: "item122"},
{id: 123, name: "item123"}
]
}
]
},
{
id: 2,
name: "item2",
children: [
{id: 21, name: "item21"},
{id: 22, name: "item22"}
]
}
];
方法:
1.使用递归函数进行深度优先遍历
function getAllChildren(items) {
let children = [];
items.forEach(item => {
children.push(item);
if (item.children) {
children = children.concat(getAllChildren(item.children));
}
});
return children;
}
// 调用函数
const allChildren = getAllChildren(items);
console.log(allChildren);
2.使用 reduce 递归方法进行深度优先遍历
function getAllChildren(items) {
return items.reduce((acc, item) => {
const { children = [], ...rest } = item;
return [...acc, rest, ...getAllChildren(children)];
}, []);
}
// 调用函数
const allChildren = getAllChildren(items);
console.log(allChildren);
3.使用 flatMap 方法进行深度优先遍历
function getAllChildren(items) {
return items.flatMap(item => {
const { children = [], ...rest } = item;
return [rest, ...getAllChildren(children)];
});
}
// 调用函数
const allChildren = getAllChildren(items);
console.log(allChildren);
这些方法都会遍历整个嵌套对象数组,并返回包含所有 children 的数组。请注意,使用递归方法时要小心,确保没有无限循环。