zoukankan      html  css  js  c++  java
  • 在不知道顶级节点的情况下,如何生成父子节点树(垃圾实现)


    由于项目要做旭日图,由于后端只帮我提取的数据库中扁平化的对象数组,所以需要我来进行数据处理,为了这个我还得处理一下数据,下面是我的数据处理过程,。

    // 本算法在不确定顶级节点的情况下,优先过滤出顶级节点,在进行遍历
    // 进行数据的大量缓存,用空间换时间,让生成tree的速度像柔丝般顺滑
    function generatorTree (data) {
      const value = 'value';
      const name = 'name';
      const id = 'id';
      const pid = 'pid';
      // 保存所有ID,然后找到pid没有对应节点的就是顶级节点
      const hasId = {};
      // 顶层父节点数组
      const topPIdArr = [];
      // 将每个节点对应的子节点对应起来
      const nodeToChildren = {};
      // 获取所有父ID(包括顶级节点的父ID)
      const pidSet = new Set();
      data.forEach(e => {
        // 之后通过topPIdArr数组可以通过深度遍历生成父子节点tree
        if (nodeToChildren[e[pid]]) {
          nodeToChildren[e[pid]].push({ name: e[name], value: e[value], id: e[id], children: [] });
        } else {
          nodeToChildren[e[pid]] = [{ name: e[name], value: e[value], id: e[id], children: [] }];
        }
        pidSet.add(e[pid]);
        hasId[e[id]] = true;
      });
      // 遍历父ID集合
      for (const pid of pidSet) {
        if (!hasId[pid]) {
          // 如果hasId没有该pid节点,说明它是顶级父节点
          topPIdArr.push(pid);
        }
      }
      // 用来存储生成的树状结构数据
      const nodeTree = [];
      // 找到所有顶级节点,开始递归生成tree,tree,tree,真的脆
      data.filter(e => topPIdArr.includes(e[pid])).forEach((e, index) => {
        nodeTree.push({ name: e[name], value: e[value], id: e[id], children: [] });
        deepCreateTree(nodeTree[index].id, nodeTree[index].children);
      });
      // 通过深度优先遍历的思路,生成父子Tree
      function deepCreateTree (id, children) {
        if (nodeToChildren[id]) {
          // 如果你不想改变nodeToChildren,建议深拷贝一下,当然里面如果属性有undefined,函数或者symbol那你得自己实现一个深拷贝方法
          const copyNodeToChildren = JSON.parse(JSON.stringify(nodeToChildren[id]));
          children.push(...copyNodeToChildren);
          copyNodeToChildren.forEach(e => {
            deepCreateTree(e.id, e.children);
          });
        }
      }
      return nodeTree;
    }
    
    generatorTree([
      {id: 1, value: 2, name: 'A', pid: 0},
      {id: 2, value: 2, name:'B', pid: 1},
      {id: 3, value: 2, name:'C', pid: 2},
      {id: 4, value: 2, name:'D', pid: 3},
      {id: 5, value: 2, name:'E', pid: 0}
      ]);
    
  • 相关阅读:
    Console命令详解,让调试js代码变得更简单
    Css中常用中文字体的Unicode编码对照
    【JQuery】性能优化方法
    document.querySelector和querySelectorAll方法
    JavaScript获取手机屏幕翻转方法
    内层元素设置position:relative后父元素overflow:hidden overflow:scroll失效 解决方法
    【JQuery Zepto插件】图片预加载
    【JQuery插件】元素根据滚动条位置自定义吸顶效果
    【JQuery插件】团购倒计时
    禁止浏览器上下拖拽方法
  • 原文地址:https://www.cnblogs.com/smallZoro/p/12759819.html
Copyright © 2011-2022 走看看