-
Notifications
You must be signed in to change notification settings - Fork 0
/
findTreekeys.js
80 lines (76 loc) · 1.84 KB
/
findTreekeys.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
var tree = [
{
id: 5,
name: "root",
children: [{
id: 51,
name: "北京市",
children: [{
id: 511,
name: "西城区",
children: [{
id: 5111,
name: "xx居委会"
}]
}]
}]
},
{
id: 6,
name: "root",
children: [{
id: 61,
name: "北京市",
children: [{
id: 611,
name: "西城区",
children: [{
id: 6111,
name: "xx居委会"
}]
}]
}]
},
{
id: 7,
name: "root",
children: [{
id: 71,
name: "北京市",
children: [{
id: 711,
name: "西城区",
children: [{
id: 7111,
name: "xx居委会"
}]
}]
}]
}
]
function getPathByKey(value, key, arr) {
let temppath = [];
try {
function getNodePath(node){
temppath.push(node);
//找到符合条件的节点,通过throw终止掉递归
if (node[key] === value) {
throw ("GOT IT!");
}
if (node.children && node.children.length > 0) {
for (var i = 0; i < node.children.length; i++) {
getNodePath(node.children[i]);
}
temppath.pop();
}else{
temppath.pop();
}
}
for (let i = 0; i < arr.length; i++) {
getNodePath(arr[i]);
}
} catch (e) {
return temppath;
}
}
let res = getPathByKey(7111, 'id', tree);