常见的多层嵌套的数组,如下
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"},{id: 3,name: "item3",children: [{id: 31, name: "item31"},{id: 32, name: "item32"}]}]
需求1.获取每一层级的每一项,
//方法1:数组reduce()方法
function getAllChildren(items) {return items.reduce((acc, item) => {const { children = [], ...rest } = item;return [...acc, item, ...getAllChildren(children)];}, []);
}
// 调用函数
const allChildren = getAllChildren(items);
console.log(allChildren);
//方法2:使用forEach的方法获取每一项
//首先,函数定义了一个空数组children,然后遍历传入的数组,如果当前项有children,则递归调用getAllChildren函数获取所有children,最后将当前项拼接到children数组中。最后,函数返回所有的children数据的数组。
function getAllChildren(array) {let children = [];array.forEach(item => {children.push(item);if (item.children) {children = children.concat(getAllChildren(item.children));}});return children;
}
//方法3:使用 flatMap 方法进行深度优先遍历
function getAllChildren(items) {return items.flatMap(item => {const { children = [], ...rest } = item;return [rest, ...getAllChildren(children)];});
}
// 调用函数
const allChildren = getAllChildren(items);
console.log(allChildren);
结果如下:
需求2.只获取每一层级中没有children的项。
代码如下:
function getAllChildren(items){return items.reduce((pre,item)=>{// const {children=[],...rest} = item// console.log(111,children,rest)if(item.children?.length>0){ //增加条件判断,获取没有children值的项return [...pre,...getAllChildren(item.children)]}else{pre.push(item)return pre}},[])}const filterItem = this.getAllChildren(items)console.log(filterItem)
结果如下:
(需求2 只做了reduce方法的条件判断处理。其他方法同样添加条件判断即可)
请注意,使用递归方法时要小心,确保没有无限循环。
参考文章:https://blog.csdn.net/qq_22182989/article/details/130337404