jQuery以递归方式迭代对象数组并返回值

时间:2016-05-18 16:31:34

标签: javascript jquery arrays recursion

我有以下json代表网站上的页面,这些页面通过items数组包含子页面,目前包含2个顶级项目 - about和services:

var data = '[{"id":107,"name":"About Us","route":"page","slug":"about","parent":0,"module":1,"items":[{"id":118,"name":"About Sub Page","route":"page","slug":"about-sub-page","parent":107,"items":[]}]},{"id":129,"name":"Services","route":"page","slug":"services","parent":0,"module":1,"items":[{"id":174,"name":"Services sub page","route":"page","slug":"services-sub-page","parent":129,"items":[]}]}]';

我正在尝试编写一个函数,该函数以递归方式迭代对象数组(data = JSON.parse(data))并识别顶级项的索引。例如,在我的函数中,如果我使用'about'slug,它将返回0,就像'about-sub-page'一样。同样,'services-sub-page'将返回1.

我现在有这个:

data = JSON.parse(data);

function check(slug,data) {
 var result;
 $.each(data, function(index){
  if (this.slug === slug) {
    result = index;
    return false;
  }
  else {
   check(slug,this.items);
  }
 });
   return result;
 }

如果我通过顶级slu_例如

,这样可以正常工作
 var index = check('about',data);
 console.log(index); // returns 0

 var index = check('services',data);
 console.log(index); // returns 1

但是,如果我尝试使用子页面,我会得到未定义的

 var index = check('services-sub-page',data);
 console.log(index); // returns undefined

我相信我需要返回false以突破每个循环,但不确定为什么当我尝试递归使用该函数时它不起作用。

2 个答案:

答案 0 :(得分:0)

您可以使用Array#some(),因为如果满足条件,这将停止迭代。



var data = '[{"id":107,"name":"About Us","route":"page","slug":"about","parent":0,"module":1,"items":[{"id":118,"name":"About Sub Page","route":"page","slug":"about-sub-page","parent":107,"items":[]}]},{"id":129,"name":"Services","route":"page","slug":"services","parent":0,"module":1,"items":[{"id":174,"name":"Services sub page","route":"page","slug":"services-sub-page","parent":129,"items":[]}]}]';

function check(slug, data) {
    function iter(a, i) {
        if (a.slug === slug || Array.isArray(a.items) && a.items.some(iter)) {
            index = i;
            return true;
        }
    }

    var index,
        array = JSON.parse(data);

    array.some(iter)
    return index;
}

document.write(check('about', data) + '<br>');
document.write(check('services', data) + '<br>');
document.write(check('services-sub-page', data) + '<br>');
&#13;
&#13;
&#13;

答案 1 :(得分:0)

data = JSON.parse(data);

功能检查(slug,data){

var result;

$。each(data,function(index){

if(this.slug === slug){

result = index;

return false;

}

其他{

result = check(slug,this.items); //分配给结果变量

}

});

返回结果;

}