开发者

Recursively Search in JSON or Javascript Object

For example:

[{
    id:'our-purpose',
    title:'Our Purpose',
    slug:'/our-purpose',
    backgroundImage:'images/bg-our-purpose.jpg',
    showInNav:1
  },
  {
    id:'our-people',
    title:'Our People',
    slug:'/our-people',
    backgroundImage:'images/bg-our-people.jpg',
    showInNav:1,
    subpages:[
      {
        id:'attorneys',
        title:'Attorneys',
        slug:'/our-people/attorneys',
        subpages:[
          {
            id:'attorneys-cdb',
            title:'Attorneys - Carla DeLoach Bryant',
            slug:'/our-people/attorneys/carla'
          },
          {
            id:'attorneys-jad',
            title:'Attorneys - Jordan A. DeLoach',
            slug:'/our-people/attorneys/jordan'
          },
          {
            id:'attorneys-shh',
            title:'Attorneys - Sarah H. Hayford',
            slug:'/our-people/attorneys/sarah'
          },
          {
            id:'attorneys-jsp',
            title:'Attorneys - Jason S. Palmisano',
            slug:'/our-people/attorneys/jason'
          },
          {
            id:'attorneys-ldw',
            title:'Attorneys - Lindsey DeLoach Wagner',
            slug:'/our-people/attorneys/carla'
          },
        ]
      },
      {
        id:'legal-support',
        title:'Legal Support',
        slug:'/our-people/legal-support',
        subpages:[
          {
            id:'legal-support-tb',
            title:'Legal Support - Theolyn Brock',
            slug:'/our-people/attorneys/theolyn'
          },
          {
            id:'legal-support-cd',
            title:'Legal Support - Cheri DeFries',
            slug:'/our-people/attorneys/cheri'
          },
        ]
      },
 //...and so on

You'll开发者_如何转开发 notice that you could do json[1].subpages[0].subpages[0] but I don't know how deep it's going to be. This is written by a designer client of mine for an AJAX site he's building for a client. I'm trying to generate a navigation amongst other things and need to be able to:

A. Parse this recursively to build a navigation (<ul><li><a>...)

B. Search for a matching id. Like this (but this isn't recursive)[and ignore the for...in, its just for example's sake)

var matchId(id,json){
  for(x in json){
    if(json[x].id == id){ var theMatch = json[x]; break; }
  }
}


This code builds the nav for you:

function buildNavForNode(node) {
  var result = "<li id='" + node.id + "'><a href='" + node.slug + "'>" + node.title + "</a>";
  if(node.subpages == undefined) {
    return result + "</li>";
  } else {
    return result + buildNavForNodes(node.subpages) + "</li>";
  }
}


function buildNavForNodes(nodes) {
  var result = "<ul>";
  var i = 0;
  var len = nodes.length;
  for(; i < len; i++) {
    result += buildNavForNode(nodes[i]);
  }
  return result + "</ul>";
}

Here's how you'd use it:

var testData = [
  {
    id:'our-purpose',
    title:'Our Purpose',
    slug:'/our-purpose',
    backgroundImage:'images/bg-our-purpose.jpg',
    showInNav:1
  },
  {
    id:'our-people',
    title:'Our People',
    slug:'/our-people',
    backgroundImage:'images/bg-our-people.jpg',
    showInNav:1,
    subpages:[
      {
        id:'attorneys',
        title:'Attorneys',
        slug:'/our-people/attorneys',
        subpages:[
          {
            id:'attorneys-cdb',
            title:'Attorneys - Carla DeLoach Bryant',
            slug:'/our-people/attorneys/carla'
          },
          {
            id:'attorneys-jad',
            title:'Attorneys - Jordan A. DeLoach',
            slug:'/our-people/attorneys/jordan'
          },
          {
            id:'attorneys-shh',
            title:'Attorneys - Sarah H. Hayford',
            slug:'/our-people/attorneys/sarah'
          },
          {
            id:'attorneys-jsp',
            title:'Attorneys - Jason S. Palmisano',
            slug:'/our-people/attorneys/jason'
          },
          {
            id:'attorneys-ldw',
            title:'Attorneys - Lindsey DeLoach Wagner',
            slug:'/our-people/attorneys/carla'
          },
        ]
      },
      {
        id:'legal-support',
        title:'Legal Support',
        slug:'/our-people/legal-support',
        subpages:[
          {
            id:'legal-support-tb',
            title:'Legal Support - Theolyn Brock',
            slug:'/our-people/attorneys/theolyn'
          },
          {
            id:'legal-support-cd',
            title:'Legal Support - Cheri DeFries',
            slug:'/our-people/attorneys/cheri'
          },
        ]
      }
    ]
  }
];

$(function(){
  htmlToInsert = buildNavForNodes(testData);
  console.log(htmlToInsert);
  $('body').html(htmlToInsert);
});

You can do this quite readily with a recursive function, but I think this nicely delineates the separation of duties between figuring out what to do with a collection of pages and processing a single page itself.


Here's a start (in some mix of JavaScript and pseudocode):

function createMenu(data) {
    create UL
    for each item in data {
        create LI for item in UL
        if the item has subpages {
            append createMenu(item.subpages) to the LI
        }
    }
    return UL
}

function findByID(data, id) {
    for each item in data {
        if(item.id==id) {
            return the item
        }
        if item has subpages {
            if findByID(item.subpages, id) is not null, return the result
        }
    }
    return null;
}


function matchId(id, json){
  if (!(json && "object" === typeof json)) { return; }
  if (json.id === id) { return json; }
  for (var x in json){
    if (Object.hasOwnProperty.call(json, x)) {
      var result = matchId(id, json[x]);
      if (result !== undefined) { return result; }
    }
  }
}


I would give a try for JSONPath you can find the code here.


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

$('#sidebar').append('<ul></ul>');

for(x in PAGES){
  if(PAGES[x].showInNav == 1){
    $('#sidebar > ul').append('<li data-id="'+PAGES[x].id+'"><a href="#!'+PAGES[x].slug+'">'+PAGES[x].title+'</a></li>');
    if(PAGES[x].subpages){
      $('#sidebar > ul > li:last').append('<ul></ul>');
      for(y in PAGES[x].subpages){
        $('#sidebar > ul > li:last > ul').append('<li data-id="'+PAGES[x].subpages[y].id+'"><a href="#!'+PAGES[x].subpages[y].slug+'">'+PAGES[x].subpages[y].title+'</a></li>');
      }
    }
  }
}

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;
      }
    }
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜