简体   繁体   English

如何遍历包含对象的对象?

[英]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 . 我正在尝试使用以上代码从位于sport.stats.position.stat_group内的每个对象中获取属性key 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: 这就是我想要的结果stats对象为:

{
    "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. 因为...在javascript中为您提供了对象的键,而不是值。

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. JS for...in循环迭代键,而不是值。 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;
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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