先上代码,下面我在说我的思路
const lists=[
{ id: 3, title: '子级2',parentId:1 },
{ id: 2, title: '子级1',parentId:1 },
{ id: 1, title: '父级1' },
{ id: 4, title: '父级2' },
{ id: 5, title: '子级3', parentId: 4 },
{ id: 6, title: '子级4', parentId: 5 },
]
//拿到父级数组
const list2 = lists.filter(it => !it.parentId && it.parentId !== 0)
let res;
//递归的方法
const roback1 = (entity1: any, child: any) => {
entity1.forEach(it => {
//给it添加children属性
it.children = [];
let en=[];
child.forEach(ch => {
if (ch.parentId && ch.parentId === it.id) {
it.children.push(ch);
en.push(ch)
}
})
//调用自身实现递归
roback1(en,child)
})
res = entity1;
}
roback1(list2, lists)
console.log(res)
首先得到一个扁平型的数据,要找到一个切入点,就是最上层的父级(就是再往上找没有父级了)
1.拿到父级数组,即id是1和4的两个数据组成的数组
2.遍历父级数组(list2),遍历的同时循环遍历总的数据(lists)
3.当list2.id==lists.parentId时,将lists的数据添加到list2的children中
4.调用自身,向下一层添加children
5.有些东西描述不出来还请见谅