js递归遍历树形json数据,根据关键字查找节点


var nodes = [{id:1,name:1,children:[{id:4,name:4}]}]

实现方式

//递归实现
//@leafId  查找的id,
//@nodes   原始Json数据
//@path    供递归使用
function findPathByLeafId(leafId, nodes, path) {
  if(path === undefined) {
    path = [];
  }
  for(var i = 0; i < nodes.length; i++) {
      var tmpPath = path.concat();
      tmpPath.push(nodes[i].id);
      if(leafId == nodes[i].id) {
         return tmpPath;
      }
      if(nodes[i].children) {
        var findResult = findPathByLeafId(leafId, nodes[i].children, tmpPath);
        if(findResult) {
          return findResult;
        }
      }
  }
}

使用 

console.log(findPathByLeafId(4, nodes))

改造
获取整个obj数据
function findPathByLeafId(leafId, nodes, path){
    if(path === undefined) {
        path = {};
      }
      for(var i = 0; i < nodes.length; i++) {
          var tmpPath = path;
        //   tmpPath.push(nodes[i].id);
          if(leafId == nodes[i].id) {
            tmpPath=nodes[i];
            return tmpPath;
          }
          if(nodes[i].children) {
            var findResult = findPathByLeafId(leafId, nodes[i].children,  tmpPath);
            if(findResult) {
              return findResult;
            }
          }
      }
}

 

 

原文:https://blog.csdn.net/m0_37727560/article/details/91607575


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM