数组转化成树结构数据

133 阅读1分钟

将数组数据转化成树形数据结构

  1. 层序便利方法1
function toTree(array: any[]) {
  const gByPids: Map<string, any> = array.reduce((acc, item) => {
    if (!acc.has(item.parentId)) {
      acc.set(item.parentId, [item]);
    } else {
      acc.get(item.parentId).push(item);
    }
    return acc;
  }, new Map());

  function toTreeData(nodes?: any) {
    if (!nodes) {
      nodes = gByPids.get(null) || gByPids.get(undefined);
    }
    nodes.forEach((tnode: any) => {
      if (gByPids.has(tnode.id)) {
        tnode.children = gByPids.get(tnode.id);
        toTreeData(tnode.children);
      }
    });
    return nodes;
  }

  return toTreeData();
}

const res = toTree([
  { parentId: null, title: "sdfs", id: "1" },
  { parentId: "1", title: "sdfs", id: "2" },
  { parentId: "1", title: "sdfs", id: "3" },
  { parentId: "3", title: "sdfs", id: "4" },
]);