使用js在树形(tree)结构中找到子节点的父级路径
# 核心方法
function findIndexArray(data, id, indexArray) {
let arr = Array.from(indexArray)
for (let i = 0, len = data.length; i < len; i++) {
arr.push(data[i].pid)
if (data[i].id === id) {
return arr
}
let children = data[i].children
if (children && children.length) {
let result = findIndexArray(children, id, arr)
if (result) return result
}
arr.pop()
}
return false
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 使用案例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS-如何在JSON树形结构中找到子节点的父级路径</title>
<script>
const data = [{
id: 11,
pid: 'a1',
text: 11,
children: [{
id: 21,
pid: 'b1',
text: 21,
children: [{
id: 31,
pid: 'c1',
text: 31,
children: [{
id: 41,
pid: 'd1',
text: 41,
children: []
},
{
id: 42,
pid: 'd2',
text: 42,
children: []
}
]
},
{
id: 32,
pid: 'c2',
text: 32,
children: []
}
]
},
{
id: 22,
pid: 'b2',
text: 22,
children: []
}
]
},
{
id: 12,
pid: 'a2',
text: 12,
children: []
}
]
function findIndexArray(data, id, indexArray) {
let arr = Array.from(indexArray)
for (let i = 0, len = data.length; i < len; i++) {
arr.push(data[i].pid)
if (data[i].id === id) {
return arr
}
let children = data[i].children
if (children && children.length) {
let result = findIndexArray(children, id, arr)
if (result) return result
}
arr.pop()
}
return false
}
console.log(findIndexArray(data, 42, [])) // ["a1", "b1", "c1", "d2"]
</script>
</head>
<body></body>
</html>
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
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
上次更新: 2024/01/30, 00:35:17
- 02
- Node与GLIBC_2.27不兼容解决方案08-19
- 03
- Git清空本地文件跟踪缓存08-13