Javascript Reduce方法,以便使用特定键计算对象值

Javascript Reduce方法,以便使用特定键计算对象值,javascript,arrays,javascript-objects,Javascript,Arrays,Javascript Objects,我有这样一个数组: 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

我有这样一个数组:

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},{,
结果=团队点数减少((a,c)=>{
设keys=Object.keys(c),
[键]=键[0]。拆分(“”);
a[键]=(a[键]| | 0)+c[键[0];
返回a;
}, {});
控制台日志(结果)

.as控制台包装{max height:100%!important;top:0;}
这里是一个使用
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 scoresult=teamsPoints.reduce((总数,游戏)=>{
const[gameName]=Object.keys(游戏);
const[team]=gameName.split(“"”);
总计[团队]=总计[团队]| 0;
总计[团队]+=游戏[游戏名称];
返回总数;
}, {});

console.log(scoresult)所以一般来说我不会使用reduce,因为对象是如何组织的。你不会真的想在同一个对象中指明哪场比赛和哪支球队,但是如果你有这样的对象,我会首先创建第二个对象来存储总数,然后执行以下操作

let totals = {};

teamsPoints.map(obj => {
  Object.keys(obj).map(key => {
    if (totals.hasOwnProperty(key.split('_')[0])) {
       totals[key.split('_')[0]] += obj[key];
    } else {
      totals[key.split('_')[0]] = obj[key];
    }
  });
});

我希望首先映射数组,以便有一组:


只有一个问题:为什么在这里使用括号:const[gameName]?或者这样做:
const[gameName]=Object.keys(游戏)或此:
constgamename=Object.keys(游戏)[0]第一个更现代、更优雅:)它是最后一个ES功能的一部分:
const res = teamsPoints
    .map(val => Object.entries(val)[0])
    .map(([key, val]) => [key.split('_')[0], val])
    .reduce((init, [team, count]) => Object.assign(init, { [team]: (init[team] || 0) +  count }), {});