使用具有相同ID的对象添加数组分数

时间:2018-04-10 16:35:58

标签: 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)

这将返回[]

1 个答案:

答案 0 :(得分:5)

您可以这样使用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);