数据转树形结构

数据转树形结构

一、需求

将如下数据转化为树形结构。以下数据关联性为id为自身唯一标识,parentid为关联的父级id。parentid若为0则为最*,没有父级。

 

 1 [
 2       {
 3         id: 1,
 4         parentid: 0,
 5         value: 'aaa'
 6       },
 7       {
 8         id: 2,
 9         parentid: 0,
10         value: 'bbb'
11       },
12       {
13         id: 3,
14         parentid: 0,
15         value: 'ccc'
16       },
17       {
18         id: 4,
19         parentid: 2,
20         value: 'ddd'
21       },
22       {
23         id: 5,
24         parentid: 2,
25         value: 'eee'
26       },
27       {
28         id: 6,
29         parentid: 5,
30         value: 'fff'
31       },
32       {
33         id: 7,
34         parentid: 6,
35         value: 'fff'
36       },
37       {
38         id: 8,
39         parentid: 7,
40         value: 'fff'
41       },
42       {
43         id: 9,
44         parentid: 5,
45         value: 'fff'
46       },
47 ]

 

二、转化处理

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <script>
    var arr = [
      {
        id: 1,
        parentid: 0,
        value: 'aaa'
      },
      {
        id: 2,
        parentid: 0,
        value: 'bbb'
      },
      {
        id: 3,
        parentid: 0,
        value: 'ccc'
      },
      {
        id: 4,
        parentid: 2,
        value: 'ddd'
      },
      {
        id: 5,
        parentid: 2,
        value: 'eee'
      },
      {
        id: 6,
        parentid: 5,
        value: 'fff'
      },
      {
        id: 7,
        parentid: 6,
        value: 'fff'
      },
      {
        id: 8,
        parentid: 7,
        value: 'fff'
      },
      {
        id: 9,
        parentid: 5,
        value: 'fff'
      },
    ]
    function setTreeData(source) {
      let cloneData = JSON.parse(JSON.stringify(source))
      return cloneData.filter(father => {
        let branchArr = cloneData.filter(child=> father.id === child.parentid)
        branchArr.length > 0 ? (father.children = branchArr) : ''
        return father.parentid == 0
      })
    }
    console.log(setTreeData(arr));
  </script>
</body>
</html>
以上setTreeData函数会生成对应的树形结构且没有层级限制。
上一篇:P1339 [USACO09OCT]热浪Heat Wave(SPFA)


下一篇:2022GDUT寒训专题三