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

原文地址:https://www.cnblogs.com/webqiand/p/12973159.html