user593029
user593029

Reputation: 521

How to make JSON recursion work

I wrote a conventional recursive loop but when the condition is satisfied it does not return the value but still continues to loop. I tried to break but it does not stop.

My code and JSON are below. However I see on the console that the value is getting populated once as expected when the id is "2". Also dip search is done correctly as well but when I inspect the returned object by the function which calls the util.iterate(json) the value of the calling function object is 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"
    }]
}

Upvotes: 0

Views: 102

Answers (2)

standup75
standup75

Reputation: 4814

You need to return the result if you find one:

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

See: http://jsfiddle.net/tKFe2/

Upvotes: 2

Markku K.
Markku K.

Reputation: 3908

I think you are missing a return:

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

Upvotes: 1

Related Questions