js list转tree 和 tree转list

摘要:项目必用的数据结构转换;
1、 list转tree (效率最高的方式)

   /**
     * json格式转树状结构
     * @param   {json:json}      json数据
     * @param   {idStr:String}    id的字符串
     * @param   {pidStr:String}    parentId的字符串
     * @param   {chindrenStr:String}    children的字符串
     * @return  {result:Array}     数组
     */
    transData(json, idStr, pidStr, chindrenStr) {
      const jsonBak = JSON.parse(JSON.stringify(json));
      var r = [],
        hash = {},
        id = idStr,
        pid = pidStr,
        children = chindrenStr,
        i = 0,
        j = 0,
        len = jsonBak.length;
      // 利用对象将数据进行缓存提高检索效率
      for (; i < len; i++) {
        hash[jsonBak[i][id]] = jsonBak[i];
      }

      for (; j < len; j++) {
        var aVal = jsonBak[j],
          hashVP = hash[aVal[pid]];
        if (hashVP) {
          let isPush = true;
          !hashVP[children] && (hashVP[children] = []);
          // 如果数据存在重复数据 则不添加 (根据需要添加这段代码)
          for (const item of hashVP[children]) {
            if (item.id == aVal.id) {
              isPush = false;
            }
          }
          isPush === true ? hashVP[children].push(aVal) : "";
        } else {
          r.push(aVal);
        }
      }
      return r;
    },

2、 tree转list
 

treeToList(tree) {
      var list = []; //结果lsit
      for (var i in tree) {
        var node = tree[i];
        if (!node.children) {
          node.children = [];
        }
        if (node.children && node.children.length !== 0) {
          list.push(node);
          this.toListDF(node.children, list, node.id); //遍历子树,并加入到list中.
        } else {
          list.push(node);
        }
      }
      return list;
    },
    toListDF(tree, list, parentId) {
      for (var i in tree) {
        var node = tree[i];
        if (!node.children) {
          node.children = [];
        }
        list.push(node);
        //如果有子结点,再遍历子结点
        if (node.children && node.children.length !== 0) {
          list.push(node.children);
          this.toListDF(node.children, list, node.id); //递归
        }
      }
    },

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值