0

I have a JavaScript object:

var testJSON = {
    "Divisions": {
        "modes": [{
            "number": 1,
            "name": "Fruits",
            "Fruits": [{

                "name": "Mango",

                "Mango": [{
                    "number": 1,
                    "name": "Nagpur"
                }]
            }]
        }, {
            "number": 4,
            "name": "Coffee",
            "Coffee": [{

                "name": "Germany",
                "Germany": [{
                    "number": 1,
                    "name": "Germany"
                }]

            }, {

                "name": "Italy",
                "Italy": [{
                    "number": 1,
                    "name": "Italy"
                }]
            },

            ]
        }, {
            "number": 5,
            "name": "Burger",
            "Burger": [{
                "number": 2,
                "name": "McDonalds"
            }, {
                "number": 1,
                "name": "Ham"
            }]
        }]

    }
};

I want to get the value of "name" in each level to different arrays..

I have tried the code

function recursion(input)
    {
        var arrayLength=input.Divisions.modes.length;

        for(var i=0;i<arrayLength;i++)
            {
                var elem = input[i];


                if(input[i].name==undefined);   
                {       
                    return;
                }


                recursion(elem);


        }



}

var c=recursion(testJSON);

This doesn't work. I guess its the recursion part that I'm doing wrong. The level of object is not a fixed one.

craig_h
  • 31,871
  • 6
  • 59
  • 68
user1371896
  • 2,192
  • 7
  • 23
  • 32
  • That's not JSON, that is a JavaScript object. And proper indentation helps to recognize the structure better. – Felix Kling May 07 '12 at 11:02
  • possible duplicate of [traversing through JSON string to inner levels using recursive function](http://stackoverflow.com/questions/10459917/traversing-through-json-string-to-inner-levels-using-recursive-function). How is this question different from the last one? – Sirko May 07 '12 at 11:04
  • that used the key value to traverse thru inner levels.. I would like to know how it can be done using an array... – user1371896 May 07 '12 at 11:06
  • How is this code related to your object? You are testing for an `entity` property but none of the objects has such a property. Also your function does not return anything or extract any data, so how did you expect it "to work"? – Felix Kling May 07 '12 at 11:06
  • code is related to my object, Ive added that part.. I am clueless about traversing in to inner levels using array.. – user1371896 May 07 '12 at 11:08

0 Answers0