美文网首页
2021-08-09 数组扁平化

2021-08-09 数组扁平化

作者: 0说 | 来源:发表于2021-08-09 17:11 被阅读0次
function arrayToTree(items) {
      const result = []; // 存放结果集
      const itemMap = {}; //
      for (const item of items) {
        const id = item.id;
        const pid = item.pid;

        if (!itemMap[id]) {
          itemMap[id] = {
            children: [],
          };
        }

        itemMap[id] = {
          ...item,
          children: itemMap[id]["children"],
        };

        const treeItem = itemMap[id];

        if (pid === 0) {
          result.push(treeItem);
        } else {
          if (!itemMap[pid]) {
            itemMap[pid] = {
              children: [],
            };
          }
          itemMap[pid].children.push(treeItem);
        }
      }
      return result;
    }
    let arr = [
      { 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 },
    ];
    
    console.log(arrayToTree(arr))
image.png

相关文章

网友评论

      本文标题:2021-08-09 数组扁平化

      本文链接:https://www.haomeiwen.com/subject/fhnzvltx.html