数组转树

28 阅读1分钟
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      let arr = [
        { id: 1, pid: 100, name: "A" }, // pid=100 不存在 → 根
        { id: 2, pid: 1, name: "B" },
        { id: 3, pid: 1, name: "C" },
      ];
      function arrayToList(arr) {
      // 先遍历一遍,把每个节点存到 map
        const map = new Map();
        const result = [];
        arr.forEach((item) => {
          map[item.id] = { ...item, children: [] };
        });
        // 第二遍,把节点塞进父节点
        arr.forEach((item) => {
          const node = map[item.id];
          if (!map[item.pid]) {
            result.push(node);
          } else {
            map[item.pid].children.push(node);
          }
        });
        return result;
      }

      console.log(arrayToList(arr));
    </script>
  </body>
</html>