3

I have a json data like this,

var menuItems = {
    data:
    {        
        dataA: 
        {
            cmClass: "classA",
            cmID: "a",
            properties: [
                { cId: 'testa', cClass: 'edit', aId: 'sa', text: 'sample a' },
                { cId: 'testaa', cClass: 'cut', aId: 'saa', text: 'sample aa' }                
            ]
        },
        dataB: 
        {
            cmClass: "classB",
            cmID: "b",
            properties: [
                { cId: 'testb', cClass: 'edit', aId: 'sb', text: 'sample b' },
                { cId: 'testbb', cClass: 'cut', aId: 'sbb', text: 'sample bb' },
                { cId: 'testbbb', cClass: 'copy', aId: 'sbbb', text: 'sample bbb' },
            ]
        }
    }
};

I want to loop through all the data and create a unordered list out of it. So for testing im having the following jquery,

    $.each(menuItems.data, function (i) {
    $.each(this, function (key, value) {
    {
        alert(key + " : " + value);
        if (key == "properties") {
            $.each(value, function (key1, value1) {
                alert(key1 + " : " + value1);
            })
        }
    }
    });          
});

the first alert is showing properly as "cmClass : classA", "cmId : a" etc., but the second loop it is always giving "0 : [object object]", "1 : [object object]" etc., Im stuck here, i tried different cases but nothing seem to work. Is it anything wrong with the json data? can anybody help? im stuck here

2
  • 1
    Much easier to debug if you use console.log instead of alert. Commented Feb 14, 2013 at 9:39
  • thx.. thts a good one... but the solution for actual question? Commented Feb 14, 2013 at 9:42

1 Answer 1

2

You loop over objects, therefore you need to do another loop inside the $each.

$.each(menuItems.data, function (i) {
    $.each(this, function (key, value) {
    {
        console.log(key + " : " + value);
        if (key == "properties") {
            $.each(value, function (key1, value1) {
                for(k in value1) {
                   console.log( key1 + ':' + k + ':' + value1[k]);
                }
            })
        }
    }
    });
});
Sign up to request clarification or add additional context in comments.

4 Comments

just one doubt, how can i access like cmClass, cmId instead of generically accessing from variables?
@Reuben when you know the parent key you could do it by: menuItems.data.dataA.cmClass
yes michel, i understand tht.. but wen we r looping, is it possible to say this.cId in the second loop? because it is giving as 'undefined' for me..
sorry for the previous comment.. i misplaced it in the wrong place.. it is working perfect.. thanks a lot :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.