Confusion when looping multidimensional json array using jquery
I have 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 data and create an unordered list from 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 warning correctly displays as "cmClass: classA", "cmId: a", etc., but in the second loop it always gives "0: [object object]", "1: [object object]", etc. .., I am stuck here, I have tried different cases but nothing seems to work. Is this something wrong with the json data? can anyone help? I'm stuck here
+3
source to share
1 answer
You are iterating over objects, so you need to do another loop inside $ 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]);
}
})
}
}
});
});
+2
source to share