美文网首页
树形转换

树形转换

作者: peerben | 来源:发表于2019-04-12 15:20 被阅读0次

如何将 [ {id: 1}, {id:2, pid:1}...] 的重复数组(有重复数据) 转成树形结构的数组
[ { id: 1, child: [ {id: 2, pid:1}] }...] 需要去重


const flatTree = [
  {id: 1},
  {id: 2, pid: 1},
  {id: 3, pid: 2},
  {id: 4, pid: 2},
  {id: 5, pid: 1},
  {id: 6, pid: 4},
];

function findNode(nodeList: any, id: number) : any {
  if (!id) return { find: false };

  for (const n of nodeList) {
    if (n.id === id) return { find: true, node: n };
    if (n.child) return findNode(n.child, id);
  }

  return { find: false };
}

function converToTree(ftree: any[]) {
  const deepTree: any[] = [];

  ftree.forEach((node) => {
    const { find, node: n } = findNode(deepTree, node.pid);

    if (find) {
      const childList = n.child || [];
      childList.push(node);
      n.child = childList;
    } else {
      deepTree.push(node);
    }
  });

  return deepTree;
}

const deepTree = converToTree(flatTree);
console.log(`deepTree ${JSON.stringify(deepTree)}`);

相关文章

网友评论

      本文标题:树形转换

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