如题:
请添加图片描述
实现代码

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
let json1 = [
{
id: 1
},
{
id: 2,
parentId: 1
},
{
id: 3
},
{
id: 4,
parentId: 3
},
{
id: 5,
parentId: 4
}
]

function set(list) {
// 获取父数据
let parents = list.filter(item => !item.parentId)
// 获取父数据
let childs = list.filter(item => item.parentId)
function setTreeList(parents, childs) {
parents.forEach((par, i) => {
childs.forEach((chil, j) => {
// 如果父id和子数据的parentId相同则往父数据的childs属性上赋值
if (par.id === chil.parentId) {
par.childs = par.childs ? par.childs.push(chil) : [chil]
// 拷贝一份子数据
let newChilds = JSON.parse(JSON.stringify(childs))
// 将当前已经找到的数据删除掉,递归继续遍历,提高运行效率
newChilds.splice(j, 1)
// 递归遍历,拿着当前的子数据去找是否还有三级数据
setTreeList([chil], newChilds)
}
})
});
}
setTreeList(parents, childs)
return parents;
}

console.log(JSON.stringify(set(json1), null, 2));

运行效果:
在这里插入图片描述