我有一个这样的数组:
const teamsPoints = [
{team1_game00: 1},
{team1_game01: 2},
{team1_game02: 3},
{team2_game00: 0},
{team2_game10: 2},
{team2_game11: 3},
{team3_game01: 0},
{team3_game10: 0},
{team3_game20: 3},
{team4_game02: 0},
{team4_game11: 0},
{team4_game20: 0}
]
我想得到的是:
{
team1: 6,
team2: 5,
team3: 3,
team4: 0
}
这是每支队伍的总分。
我试图通过使用 reduce 方法来实现这一点。
const scoreResult = teamsPoints.reduce((total, current) => {
}, {});
据我所知,我是从一个空对象开始的,但是后来我在获取正确的键值对时遇到了问题(这就是为什么我没有在这里发布它,必须 admin reduce 方法对我来说是一个新事物) .
提前致谢!
最佳答案
这是一个使用reduce
的小示例。我基本上得到了团队的名称,将其用作缩减结果中的键并增加其值!
希望这对您有所帮助;)如果有任何不清楚的地方,请随时问我!
const teamsPoints = [
{team1_game00: 1},
{team1_game01: 2},
{team1_game02: 3},
{team2_game00: 0},
{team2_game10: 2},
{team2_game11: 3},
{team3_game01: 0},
{team3_game10: 0},
{team3_game20: 3},
{team4_game02: 0},
{team4_game11: 0},
{team4_game20: 0}
];
const scoreResult = teamsPoints.reduce((total, game) => {
const [gameName] = Object.keys(game);
const [team] = gameName.split('_');
total[team] = total[team] || 0;
total[team] += game[gameName];
return total;
}, {});
console.log(scoreResult);
关于javascript - Reduce 方法以计算具有特定键的对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51381037/