如何使JSON递归工作

时间:2013-05-20 20:05:09

标签: javascript json

我编写了一个传统的递归循环但是当条件满足时它不返回值但仍然继续循环。我试图打破,但它并没有停止。

我的代码和JSON如下。但是我在控制台上看到,当id为“2”时,值将按预期填充一次。也可以正确完成dip搜索,但是当我通过调用util.iterate(json)的函数检查返回的对象时,调用函数对象的值为undefined

util.iterate = function (obj){
    for(var i in obj)
    {
        if( i === "id" && obj[i] === "2"){
            console.log("test" +obj[i]  );
            return obj;
            //break; does not work either
        }
        else if (typeof(obj[i])=="object"){
            this.iterate(obj[i]);
        }
    }
}

JSON:

{
    "id": "0",
    "item": [{
        "id": "1",
        "text": "1111",
        "userdata": [{
            "name": "name",
            "content": "BK"
        }]
    },
    {
        "id": "2",
        "select": "1",
        "text": "222222",
        "item": [{
            "id": "21",
            "text": "child"
        }]
    },
    {
        "id": "3",
        "text": "3333"
    }]
}

2 个答案:

答案 0 :(得分:2)

如果找到结果,则需要返回结果:

util.iterate = function (obj){
        for(var i in obj)
        {
               if( i === "id" && obj[i] === "2"){
                   console.log("test" +obj[i]  );
                   //ffmodifierutil.storeObj = obj;
                  return obj;
                  //break; does not work either
                }
               else if (typeof(obj[i])=="object"){
                   var res = this.iterate(obj[i]);
                   if (res) return res;
               }
        }
    }

请参阅:http://jsfiddle.net/tKFe2/

答案 1 :(得分:1)

我认为你错过了return

    else if (typeof(obj[i])=="object"){
        return this.iterate(obj[i]);
    }// ^^^^^^