# 打平的数组转成树形数组

const arr = [
  { id: 1, parentId: null },
  { id: 2, parentId: 1 },
  { id: 3, parentId: 2 },
  { id: 5, parentId: 3 },
  { id: 6, parentId: 3 },
];

const arr1 = {
  id: 1,
  parentId: null,
  children: [
    {
      id: 2,
      parentId: 1,
      children: [
        {
          id: 3,
          parentId: 2,
          children: [
            { id: 5, parentId: 3, children: [] },
            { id: 6, parentId: 3, children: [] },
          ],
        },
      ],
    },
  ],
};

// function arrToTree(arr) {
//   for (let i = 0; i < arr.length; i++) {
//     const cur = arr[i];
//     cur.children = arr.filter((item) => item.parentId === cur.id);
//   }

//   console.log(JSON.stringify(arr[0]));
// }

function treeToArr(tree) {
  const arr = [];
  setArrItem(arr, [tree]);
  function setArrItem(arr, treeArr, parentId = null) {
    treeArr.forEach((tree) => {
      arr.push({ id: tree.id, parentId });
      if (Array.isArray(tree.children) && tree.children.length > 0) {
        setArrItem(arr, tree.children, tree.id);
      }
    });
  }

  return arr;
}

console.log(treeToArr(arr1));
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
Last Updated: 6/27/2023, 7:40:45 PM