javascript - 添加具有相同 ID 的对象的数组分数

标签 javascript

我有一个对象数组:

console.log(quizNight[0].round[--latestRound].t)
 -> [ { teamID: 16867, correctAnswers: 1 },
      { teamID: 16867, correctAnswers: 1 },
      { teamID: 16867, correctAnswers: 1 } ]

我希望有一个 correctTotalAnswers 数组看起来像这样:

[ { teamID: 16867, correctTotalAnswers: 3} ]

最明智的做法是什么?我现在拥有的代码:

let correctAnswersArrayRoung = quizNight[0].round[--latestRound].t;
let totalCorrentAnswersArray = [];
for (let correctAnswer in correctAnswersArrayRoung) {
   console.log(correctAnswersArrayRoung[correctAnswer])
   for(let element in totalCorrentAnswersArray){
      if(element.teamID === correctAnswer.teamID){
         element.totalCorrectAnswers = ++element.totalCorrectAnswers
      } else {
         totalCorrentAnswersArray.push({
            teamID: correctAnswer.teamID,
            totalCorrectAnswers: 1
         })
      }
   }
}
console.log(totalCorrentAnswersArray)

返回 []

最佳答案

你可以这样使用reduce(见内联注释):

// Your initial data
const initialArray = [
  { teamID: 16867, correctAnswers: 1 },
  { teamID: 16867, correctAnswers: 1 },
  { teamID: 16866, correctAnswers: 1 }
]

// Use reduce to loop through the data array, and sum up the correct answers for each teamID
let result = initialArray.reduce((acc, c) => {
  // The `acc` is called "accumulator" and it is
  // your object passed as the second argument to `reduce`
  
  // We make sure the object holds a value which is
  // at least `0` for the current team id (if it exists,
  // it will be used, otherwise will be initialized to 0)
  acc[c.teamID] = acc[c.teamID] || 0
  
  // Sum up the correctAnswers value
  acc[c.teamID] += c.correctAnswers
  return acc
}, {}) // <- Start with an empty object

// At this point the result looks like this:
// {
//  "16866": 1,
//  "16867": 2
// }

// Finally convert the result into an array
result = Object.keys(result).map(c => ({
  teamID: c,
  correctAnswers: result[c]
}))

console.log(result);

关于javascript - 添加具有相同 ID 的对象的数组分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49758781/

相关文章:

javascript - 在javascript中将SQL数据库转换为RDF

javascript - Bokeh:在 DataTable 小部件中显示本地文件

javascript - 如何在 TypeScript 中使用第一阶段 babel 插件

javascript - 分配给原语的值将丢失

javascript - JSON数据到JS中的有效数据数组

javascript - 如何从运行 PHP 和 MySQL 的 Web 服务器读取 JSON 数据?

javascript - 基于网络的在线图表(这些软件是如何实现的)

javascript - 使用 javascript 通过 DOMContentLoaded 提供较小的图像

javascript - 使用 Javascript 在 div 元素之间切换

javascript - Backbone 或 Ember 应该用于什么类型的站点/应用程序?