扁平数组转成树形结构数组

这里对于之前的文章《树形数组扁平化》,不过还原树形数组目前在项目中尚未遇到,在这里暂做下记录

    // 还原树形结构
    restoreTree(arr, idKey = "id", parentIdKey = "parentId") {
      const map = {};
      const roots = [];

      // 将节点按照 id 存储到一个对象中
      for (const node of arr) {
        map[node[idKey]] = { ...node, children: [] };
      }

      // 遍历每个节点,将其添加到其父节点的 children 属性中
      for (const node of arr) {
        const parent = map[node[parentIdKey]];
        if (parent) {
          parent.children.push(map[node[idKey]]);
        } else {
          roots.push(map[node[idKey]]);
        }
      }

      return roots;
    },
发表评论 / Comment

用心评论~