我的目標:如何遍歷包含對象的對象?
"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"}
]
}
}
}
我的代碼:
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;
}
}
}
我嘗試使用上面的代碼從位於內sport.stats.position.stat_group
每個對象搶財產key
。每項運動有不同數量的職位和統計組,因此是三重循環。我沒有得到任何控制檯錯誤,它只是不抓取關鍵字,迭代器變量不計算對象,而是整數。
這裏就是我想要得到的stats
對象爲:
{
"statkey1": true,
"statkey2": true,
"statkey3": true,
...
}
希望你們能幫助!謝謝!
這不是'如何爲... in'工作,參見[文件](https://developer.mozilla.org /en/docs/Web/JavaScript/Reference/Statements/for...in)。另外'sport'沒有定義,我只看到'stats',它與'sport.stats'無關。我很確定「如何遍歷包含數組的對象」已被問及十多次。 – ASDFGerte
另請參閱:[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-對象數組)和其他無數的。 – ASDFGerte