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