【发布时间】:2019-03-03 07:48:52
【问题描述】:
我正在尝试对这个对象中每个杯子的比赛和参与者的总数求和:
{
"Cup_1": {
"bronze": {
"matches": 3,
"participants": 289
},
"silver": {
"matches": 20,
"participants": 1874
},
"gold": {
"matches": 35,
"participants": 3227
},
"platinum": {
"matches": 3,
"participants": 294
},
"diamond": {
"matches": 5,
"participants": 482
},
"ace": {
"matches": 6,
"participants": 574
}
},
"Cup_2": {
"bronze": {
"matches": 17,
"participants": 1609
},
"silver": {
"matches": 46,
"participants": 4408
},
"gold": {
"matches": 157,
"participants": 14391
},
"platinum": {
"matches": 0,
"participants": 0
},
"diamond": {
"matches": 5,
"participants": 469
},
"ace": {
"matches": 10,
"participants": 959
}
},
"Cup_3": {
"bronze": {
"matches": 35,
"participants": 3358
},
"silver": {
"matches": 96,
"participants": 9069
},
"gold": {
"matches": 313,
"participants": 29527
},
"platinum": {
"matches": 10,
"participants": 960
},
"diamond": {
"matches": 16,
"participants": 1538
},
"ace": {
"matches": 45,
"participants": 4280
}
},
"Cup_4": {
"bronze": {
"matches": 2,
"participants": 187
},
"silver": {
"matches": 8,
"participants": 742
},
"gold": {
"matches": 37,
"participants": 3416
},
"platinum": {
"matches": 0,
"participants": 0
},
"diamond": {
"matches": 2,
"participants": 196
},
"ace": {
"matches": 3,
"participants": 290
}
},
"Cup_5": {
"bronze": {
"matches": 89,
"participants": 1638
}
}
}
当对象内部有另一个对象时,我不知道如何对属性求和(对不起,我还没有学过);
我想要一个新对象,其中包含每个杯赛总比赛的结果和参与者总数。 还有除了 cup_5 之外的所有杯子的每个类别的总比赛和参与者,因为它只有一个类别。
类似:
Cup_1 总场次:72
Cup_1 总参与者:6740
铜牌比赛总数(所有杯赛):57;
铜牌参赛者总数(所有杯子):5443
带有结果的新对象示例:
var cups_result = {
"Total_Cup_1": {
matches: 72,
participants: 6740,
},
"Total_Bronze": {
matches: 57,
participants: 5443,
},
}
我读到这个对象属性的总和可以用.map 完成,但我不知道如何正确地使用映射对象。
如果有人能帮助我,我将不胜感激!
【问题讨论】:
-
到目前为止你有什么尝试?
-
对不起,编辑问题以反映我正在尝试对对象内的对象属性求和!
-
我不知道如何访问“青铜”、“银”等对象来获取总价值。
-
@RogerHN 使用 for in 语句循环对象的 Key。
-
我试过这个:
for (var c in cups){ console.log(c) }但它只记录每个对象的名称,如"Cup_1"
标签: javascript string function object ecmascript-6