在JSON或Javascript对象中递归搜索

Recursively Search in JSON or Javascript Object

本文关键字:递归 搜索 对象 Javascript JSON      更新时间:2023-09-26

例如:

[{
    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

你会注意到你可以做json[1].subpages[0].subpages[0],但我不知道它会有多深。这是我的一个设计师客户为他正在为客户构建的AJAX站点编写的。我想在其他东西中生成一个导航,需要能够:

。递归解析它以构建导航(<ul><li><a>...)

B。搜索匹配的id。像这样(但这不是递归的)[并忽略for...in,只是为了举例)

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

以下代码为您构建导航:

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

你可以这样使用它:

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);
});
使用递归函数可以很容易地做到这一点,但我认为这很好地描述了确定如何处理页面集合和处理单个页面本身之间的职责分离。

这是一个开始(JavaScript和伪代码的混合):

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

我会尝试JSONPath,您可以在这里找到代码。

我用下面的代码生成导航,因为我只想要第一层:

$('#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>');
      }
    }
  }
}
然后,对于递归匹配函数,我最终使用以下代码:
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;
      }
    }
  }
}