Iyas Iyas - 3 months ago 23
AngularJS Question

Access JSON Object using for loop

This is my simplified JSON file content:

{
"array": {
"Table1": [
{
"h1": 0,
"h2": 1069
},
{
"h1": 587,
"h2": 947
}
],
"Table2": [
{
"h1": 13,
"h2": 0
},
{
"h1": 30,
"h2": 0
},
{
"h1": 75,
"h2": 0
}
]
}
}


This is what my console output after Angular $http call

var data = response.data;
$log.log(data); //Object
$log.log(data.Table1); //Array
$log.log(data.Table1[0]); //Object
$log.log(data.Table1[1].h1); //587


I tried below code but failed to get the value. Please help.

for(var a in data){ //this one correctly loops 2 times
for(var d in a){ //I have problem with this one
$log.log(d.h1);
}
}

Answer

for (var a in data) a would be the key, so Table1 or Table2. The actual value is in data[a]. Also you can not traverse an Array with for (var i in xx) method, as far as I know

for(var a in data){ //this one correctly loops 2 times
   for(var d = 0; d < data[a].length; d++){
     $log.log(data[a][d].h1);
   }
}