adunn adunn - 21 days ago 8
JSON Question

How to iterate through an object containing objects?

My object:

"hockey": {
stats: {
skaters: {
regular: [
{name: "stat1", key: "statkey1"}
{name: "stat2", key: "statkey2"}
{name: "stat3", key: "statkey3"}

]
},
goalies: {
regular: [
{name: "stat1", key: "statkey4"}
{name: "stat2", key: "statkey5"}
{name: "stat3", key: "statkey6"}
]
}
}
}


My code:

var stats = [];
var key = "";
for (position in sport.stats) {
for (stat_group in position) {
for (stat in stat_group) {
key = stat.key;
stats[key] = true;
}
}
}


I'm trying to use the above code to grab the property
key
from each object located within
sport.stats.position.stat_group
. Each sport has a different number of positions and stat groups, hence the triple for loop. I'm not getting any console errors it just isn't grabbing the key at all and the iterator variables aren't evaluating to objects but integers.

Here's what I want the resulting
stats
object to be:

{
"statkey1": true,
"statkey2": true,
"statkey3": true,
...
}


Hope you guys can help! Thanks!

Answer

For...in in javascript gives you the key of the object, not the value.

According to your logic, this is what you meant to do:

var stats = {};
var key = "";
for (position in sport.stats) {
    for (stat_group in sport.stats[position]) {
        for (stat in sport.stats[position][stat_group]) {
            key = sport.stats[position][stat_group][stat].key;
            stats[key] = true;
        }
    }
}