3

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!

adunn
  • 81
  • 1
  • 6
  • this is not how `for ... in` works, see [documentation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...in). Also `sport` is not defined, i only see `stats` which has nothing to do with `sport.stats`. I am pretty sure the "how to iterate over array containing objects" has been asked more than a dozen times. – ASDFGerte Nov 15 '16 at 14:15
  • Also see: [here](http://stackoverflow.com/questions/16626735/how-to-loop-through-an-array-containing-objects-and-access-their-properties), [here](http://stackoverflow.com/questions/6565281/iterating-over-array-of-objects-javascript-odd-behaviour), [here](http://stackoverflow.com/questions/19529403/javascript-loop-through-object-array) and countless others. – ASDFGerte Nov 15 '16 at 14:24

2 Answers2

4

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;
    }
  }
}
casraf
  • 21,085
  • 9
  • 56
  • 91
2

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;
        }
    }
}
omri_saadon
  • 10,193
  • 7
  • 33
  • 58