• tree 的递归算法


    1.根据code ,寻找tree里面的选中对象

    export function getActiveNode(tree,code){ tree: [{}] // 树型结构
      let node = {};
      finds(tree,code);
      function finds(tree,code) {
        for(let i=0;i<tree.length;i++){
          if(tree[i].code == code){
            node = tree[i]
          } else {
            if(tree[i].children && tree[i].children.length>0){
              finds(tree[i].children,code)
            }
          }
        }
      }
      return node;
    }

    2. 通过code筛选组织树节点,输出 [{}]

    export function filterNode (tree, code) {
      if (!code) {return}
      let resultArr = []
      for (let i = 0; i < tree.length; i++) {
        let item = tree[i]
        if (item.code == code) {
          resultArr.push(item)
          return resultArr
        } else if (item.children && item.children.length) {
          resultArr = filterNode(item.children, code)
        }
      }
      return resultArr
    }

    3.有父子关系的数组转换成树形结构的数组

    /**
    * 该方法用于将有父子关系的数组转换成树形结构的数组
    * 接收一个具有父子关系的数组作为参数
    * 返回一个树形结构的数组 
    */
    export function translateDataToTree (data) {
      let parents = data.filter((item,index) => {return index === data.length-1})
      //有父节点的数据
      let childrens = data.filter(value => value.parentCode)
      //定义转换方法的具体实现
      let translator = (parents, childrens) => {
        parents.forEach((parent) => {
          childrens.forEach((current, index) => {
            if (current.parentCode === parent.code) {
              //对子节点数据进行深复制,这里只支持部分类型的数据深复制,对深复制不了解的童靴可以先去了解下深复制
              let temp = JSON.parse(JSON.stringify(childrens))
              //让当前子节点从temp中移除,temp作为新的子节点数据,这里是为了让递归时,子节点的遍历次数更少,如果父子关系的层级越多,越有利
              temp.splice(index, 1)
              //让当前子节点作为唯一的父节点,去递归查找其对应的子节点
              translator([current], temp)
              //把找到子节点放入父节点的childrens属性中
              typeof parent.children !== 'undefined' ? parent.children.push(current) : parent.children = [current]
              
            }
          })
        })
      }
      //调用转换方法
      translator(parents, childrens)
      //返回最终的结果
      console.log(parents)
      return parents
    }
  • 相关阅读:
    创建maven项目
    有pom.xml文件但是无法用maven构建问题
    Linux关闭防火墙,开放端口
    Java SSH远程执行Shell命令、shell脚本实现(Ganymed SSH)
    linux系统切换用户
    Looksery Cup 2015 C. The Game Of Parity —— 博弈
    Codeforces Round #105 (Div. 2) E. Porcelain —— DP(背包问题)
    Codeforces Round #198 (Div. 2) E. Iahub and Permutations —— 容斥原理
    Educational Codeforces Round 9 C. The Smallest String Concatenation —— 贪心 + 字符串
    Technocup 2017
  • 原文地址:https://www.cnblogs.com/mmzuo-798/p/13294374.html
Copyright © 2020-2023  润新知