列表转树形结构

# 列表转树形结构

请实现arrayToTree函数

// 测试
const data = [
  // 注意这里,专门把pid为1的元素放一个在前面
  { id: 2, name: '部门2', pid: 1 },
  { id: 1, name: '部门1', pid: 0 },
  { id: 3, name: '部门3', pid: 1 },
  { id: 4, name: '部门4', pid: 3 },
  { id: 5, name: '部门5', pid: 4 },
  { id: 7, name: '部门7', pid: 6 },
]

console.log(JSON.stringify(arrayToTree(data), null, 2))
/*
[
  {
    "id": 1,
    "name": "部门1",
    "pid": 0,
    "children": [
      {
        "id": 2,
        "name": "部门2",
        "pid": 1,
        "children": []
      },
      {
        "id": 3,
        "name": "部门3",
        "pid": 1,
        "children": [
          {
            "id": 4,
            "name": "部门4",
            "pid": 3,
            "children": [
              {
                "id": 5,
                "name": "部门5",
                "pid": 4,
                "children": []
              }
            ]
          }
        ]
      }
    ]
  }
]

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
function getTreeList(rootList, id, list) {
 for(let item of rootList) {
  if(item.parent === id) {
   list.push(item)
  }
 }

 for(let i of list) {
  i.children = []
  getTreeList(rootList, i.id, list)
  if(i.children.length === 0) {
   delete i.children
  }
 }

 return list
}

const res = getTreeList(rootList, null, [])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const data = [
 // 注意这里,专门把pid为1的元素放一个在前面
 { id: 2, name: '部门2', pid: 1 },
 { id: 1, name: '部门1', pid: 0 },
 { id: 3, name: '部门3', pid: 1 },
 { id: 4, name: '部门4', pid: 3 },
 { id: 5, name: '部门5', pid: 4 },
 { id: 7, name: '部门7', pid: 6 },
]

const arrayToTree = (data) => {
 let map = new Map();
 let res = [];
 data.forEach((item) => {
   if (!item.children) {
     item.children = [];
   }
   map.set(item.id, item);
 });
 data.forEach((item) => {
   if (item.pid) {
     if (map.has(item.pid)) {
       let cur = map.get(item.pid);
       cur.children.push(item);
     }
   } else {
     res.push(item);
   }
 });
 console.log('res', res)
 return res;
};

arrayToTree(data)
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
上次更新: 2022/7/26 下午6:03:32