Recursively Search in JSON or Javascript Object

前端 未结 5 761
甜味超标
甜味超标 2020-12-20 07:08

For example:

[{
    id:\'our-purpose\',
    title:\'Our Purpose\',
    slug:\'/our-purpose\',
    backgroundImage:\'images/bg-our-purpose.jpg\',
    showInNa         


        
5条回答
  •  感动是毒
    2020-12-20 07:57

    I generated the nav with this code since I only wanted the first level:

    $('#sidebar').append('
      '); for(x in PAGES){ if(PAGES[x].showInNav == 1){ $('#sidebar > ul').append('
    • '+PAGES[x].title+'
    • '); if(PAGES[x].subpages){ $('#sidebar > ul > li:last').append('
        '); for(y in PAGES[x].subpages){ $('#sidebar > ul > li:last > ul').append('
      • '+PAGES[x].subpages[y].title+'
      • '); } } } }

        Then, for the recursive match function I ended up with this code:

        var matchKey = function(k,v,j){  
          k = k || 'id';  //key
          v = v || '';    //value
          j = j || PAGES; //json
          for(x in j){
            if(j[x][k] == v){
              return j[x];
            }
            if(j[x].subpages){
              var result = matchKey(k,v,j[x].subpages);
              if(result !== undefined){
                return result;
              }
            }
          }
        }
        

      提交回复
      热议问题