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

时间:2018-07-17 12:09:53

标签: 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_game11: 0},
  {team4_game20: 0}
]

我想要得到的是:

{
  team1: 6,
  team2: 5,
  team3: 3,
  team4: 0
}

这是每个团队得分的总和。

我正试图通过使用reduce方法来实现这一目标。

const scoreResult = teamsPoints.reduce((total, current) => {    

}, {});

据我了解,我是从一个空对象开始的,但是后来我遇到了获取正确的键值对的问题(这就是为什么我没有在这里发布它,必须使用reduce方法来管理我的原因)

提前谢谢!

4 个答案:

答案 0 :(得分:3)

您可以使用功能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}],
      result = teamsPoints.reduce((a, c) => {
        let keys = Object.keys(c),
            [key] = keys[0].split('_');
        a[key] = (a[key] || 0) + c[keys[0]];
        return a;
      }, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:3)

这里是一个使用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);

答案 2 :(得分:0)

所以一般来说,我不会使用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];
    }
  });
});

答案 3 :(得分:0)

我希望首先映射数组,以便设置entries

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 }), {});