简体   繁体   中英

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM