树形结构转列表

# 树形结构转列表

请实现tree2list函数

// 测试
const data = [
  {
    "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": []
              }
            ]
          }
        ]
      }
    ]
  }
]

console.log(tree2list(data))
/*
[ 
  { id: 1, name: '部门1', pid: 0 },
  { id: 2, name: '部门2', pid: 1 },
  { id: 3, name: '部门3', pid: 1 },
  { id: 4, name: '部门4', pid: 3 },
  { id: 5, name: '部门5', pid: 4 } 
]
*/
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
const tree2list = (data) => {
 const ans = [];
 const queue = [...data]
 
 while(queue.length) {
  const node = queue.shift()
  const children = node.children
  if(children) {
   queue.push(...children)
  }
  delete node.children
  ans.push(node)
 }
 console.log(ans, 'ans')
 return ans
}

tree2list(data)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
上次更新: 2022/7/26 下午6:03:32