forked from Rain120/Web-Study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
关系数组转成树形结构对象.js
51 lines (51 loc) · 943 Bytes
/
关系数组转成树形结构对象.js
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
42
43
44
45
46
47
48
49
50
51
/**
之前面试依图等好几个公司遇到的这个问题
obj = [
{id:1,parent:null},
{id:2,parent:1},
{id:3,parent:2}
]
||
||
VV
obj2 = {
obj:{
id: 1,
parent: null,
child: {
id: 2,
parent: 1,
child: {
id: ,3,
parent: 2
}
}
}
}
**/
var obj = [
{id:3,parent:2},
{id:1,parent:null},
{id:2,parent:1},
]
function treeObj(obj) {
obj.map(item => {
if (item.parent !== null) {
obj.map(o => {
if (item.parent === o.id) {
if (!o.child) {
o.child = [];
}
o.child.push(item);
o.child = o.child;
}
});
}
});
return obj.filter(item => item.parent === null)[0]
}
function treeObj(obj) {
return obj.sort((a, b) => b.parent - a.parent).reduce((acc, cur) => (acc ? { ...cur, child: acc } : cur));
}
obj = treeObj(obj)
console.log(obj)