Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 929
adunn Avatar asked Dec 29 '25 07:12

adunn


1 Answers

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;
    }
  }
}
like image 97
casraf Avatar answered Dec 30 '25 20:12

casraf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!