Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confusion on looping json multidimensional array using jquery

Tags:

json

jquery

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

like image 926
Reuben Avatar asked Feb 21 '26 07:02

Reuben


1 Answers

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]);
                }
            })
        }
    }
    });
});
like image 134
axel.michel Avatar answered Feb 24 '26 06:02

axel.michel