adunn
adunn

Reputation: 81

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!

Upvotes: 3

Views: 6100

Answers (2)

omri_saadon
omri_saadon

Reputation: 10621

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;
        }
    }
}

Upvotes: 2

casraf
casraf

Reputation: 21684

The JS for...in loop iterates through the keys, not values. If you want to iterate an object fully, you can do so like this:

for (key in sports.stats) {
  var position = sports.stats[key];
  for (group_key in position) {
    var stat_group = position[group_key];
    for (stat_key in stat_group) {
      stat_group[stat_key] = true;
    }
  }
}

Upvotes: 4

Related Questions