扁平数组转树结构

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
<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="css/style.css" rel="stylesheet">
    </head>
    <body>
 
        <script>
            let list = [{
                    "id": 1,
                    "title": "首页",
                    "parentId": 0,
                },
                {
                    "id": 3,
                    "title": "权限管理",
                    "parentId": 2,
                },
                {
                    "id": 4,
                    "title": "页面管理",
                    "parentId": 3,
                },
                {
                    "id": 5,
                    "title": "适用组件",
                    "parentId": 0,
                },
                {
                    "id": 6,
                    "title": "json编辑器",
                    "parentId": 5,
                },
                {
                    "id": 7,
                    "title": "富文本编辑器",
                    "parentId": 5,
                },
                {
                    "id": 2,
                    "title": "系统管理",
                    "parentId": 0,
                },
                {
                    id: 8,
                    "title": "组件管理",
                    "parentId": 4
                }
            ]
 
            function setTree(list) {
                return list.filter((item) => {
                    let children = list.filter((child) => {
                        return item.id == child.parentId
                    })
                    if (children.length > 0) {
                        item['children'] = children
                    }
                    return item['parentId'] == 0
                })
            }
            console.log(setTree(list));
        </script>
    </body>
</html>

 转换前

 

 转换后

 

posted on   久居我梦  阅读(16)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示