手写数组转树原创
# 手写数组转树
// 迭代法
// 遍历所有元素
// 依次转换每一层数据
// 返回第一层
function arrayToTree(arr){
let res = [];
const all = arr.reduce((prev,cur)=>{
prev[cur.id] = cur;
return prev;
},{})
arr.forEach((item)=>{
if(item.pid==null){
res.push(item);
}
else{
if(all[item.pid]){
const p = all[item.pid];
p.children = p.children || [];
p.children.push(item);
}
}
})
return res;
}
// 递归法
// 递归转换子层数据
// 返回第一层
function arrayToTreeDfs(arr,pid=null){
return arr.reduce((prev,cur)=>{
if(cur.pid==pid){
const children = arrayToTreeDfs(arr,cur.id);
if(children) cur.children = children;
prev.push(cur);
}
return prev;
},[])
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41