Reputation: 47
I have very complex json created at server side like -
{"2013": {"11": {"A": 0, "B": 310, "C": 6}, "12": {"A": 0, "B": 281, "C": 5}}, "2014": {"1": {"A": 0, "B": 310, "C": 6}}}
Above JSON object holds the values 'A','B', and 'C' for the three months i.e current + last 2months
var data = {{=monthly_result}}; //Python variable assigned to js var
Now I want to loop through the above object in javascript. Please guide me. Found many links but not any is fully helpful. Thanks in advance!
Upvotes: 0
Views: 4162
Reputation: 15732
var obj = {"2013": {
"11": {"A": 0, "B": 310, "C": 6},
"12": {"A": 0, "B": 281, "C": 5}
},
"2014":
{"1": {"A": 0, "B": 310, "C": 6}
}
};
for(outer in obj) {
for (inner in obj[outer]) {
for(innermost in obj[item][inner]) {
alert(outer + "-->" + inner + "-->" + innermost + "-->" + obj[item][inner][innermost]);
}
}
}
Upvotes: 0
Reputation: 1758
To iterate over a "complex" object in a generic way, I would proceed like this :
(psedo code to show how it could be done)
var result = [];
function objIterate(obj, i) {
result.push([]);
for (prop in obj){
if (isObj(prop))
objIterate(prop, i+1);
else
result[i].push(obj[prop]);
}
}
var obj = yourJson;
objIterate(obj, 0);
Upvotes: 0
Reputation: 99205
You can use a for loop, here's a very simple example :
var data = {"2013": {"11": {"A": 0, "B": 310, "C": 6}, "12":
{"A": 0, "B": 281, "C": 5}}, "2014": {"1":
{"A": 0, "B": 310, "C": 6}}};
for(var year in data) {
var ydata = data[year];
for(var num in ydata) {
var ndata = ydata[num];
for(var l in ndata) {
console.log(year + ' -> ' + num + ' -> ' + l + ' = ' + ndata[l]);
}
}
}
Upvotes: 1