javascript - Reduce 方法以计算具有特定键的对象值

标签 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) => {    

}, {});

据我所知,我是从一个空对象开始的,但是后来我在获取正确的键值对时遇到了问题(这就是为什么我没有在这里发布它,必须 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/

相关文章:

javascript - 规范化对象数组中的数据 (JavaScript)

javascript - 分页悬停时的光滑幻灯片

javascript - Javascript 中的 ERR_INSECURE_RESPONSE 处理提示

c++ - 为什么第二个代码有效而第一个无效?

javascript - 找到排序数组值之间的最大差异

c++ - 我的变量不会有任何值(value)

arrays - 处理带有 Promise 的对象数组

javascript - JavaScript中的自动贩卖机功能

javascript - block 元素在它们的 block 父元素之外被解析

javascript - 如何用html和javascript显示原始图像数据?