遍历对象数组以根据其属性创建一个新对象而不重复

我有一个包含曲棍球比赛的对象数组,我需要通过它们才能在另一个对象数组中创建记分板。

我举个例子。

我会像这样的数组:

let array = [
           {team1:"Toronto", team2:"Oilers", score1:5, skore:0},
           {team1:"Toronto", team2:"Rangers", score1:3, skore:1},
           {team1:"Toronto", team2:"Penguins", score1:0, skore:1},
           {team1:"Oilers", team2:"Rangers", score1:2, skore:2},
           {team1:"Oilers", team2:"Penguins", score1:2, skore:3},
           {team1:"Rangers", team2:"Penguins", score1:0, skore:0}
           ]

我需要一个可以让我像这样的数组的函数:

let array2 = [
  {Team:"Toronto", Wins:2, Draws:0, Losses:1, ShotGoals:8, RecievedGoals:2},
  {Team:"Oilers", Wins:0, Draws:1, Losses:2, ShotGoals:4, RecievedGoals:10},
  {Team:"Penguins", Wins:1, Draws:1, Losses:2, ShotGoals:2, RecievedGoals:4},
  {Team:"Rangers", Wins:1, Draws:2, Losses:0, ShotGoals:3, RecievedGoals:2},
]

我试图用forEach遍历整个数组,并推动新的或更改array2中的现有团队,但是随着循环的进行,我无法使它随着我正在创建的array2一起工作。它也必须是动态的,因此如果扩展了第一个数组等,它仍然可以工作,而我现在暂时无法使其工作。

我假设我将不得不使用一些数组方法,但是我似乎无法弄清楚哪一个以及如何成为新方法。

非常感谢您的帮助。谢谢。

评论
小妖、精
小妖、精
let array = [
           {team1:"Toronto", team2:"Oilers", score1:5, skore:0},
           {team1:"Toronto", team2:"Rangers", score1:3, skore:1},
           {team1:"Toronto", team2:"Penguins", score1:0, skore:1},
           {team1:"Oilers", team2:"Rangers", score1:2, skore:2},
           {team1:"Oilers", team2:"Penguins", score1:2, skore:3},
           {team1:"Rangers", team2:"Penguins", score1:0, skore:0}
           ]


let result = {};

let addToTeam = (t,w,d,l)=>{
if(result[t] == null)
return result[t] = {team:t,wins:w,draws:d,losses:l}
    result[t].wins+=w
    result[t].draws+=d
    result[t].losses+=l
}

array.forEach(m => {
if(m.score1>m.skore){
    addToTeam(m.team1,1,0,0)
    addToTeam(m.team2,0,0,1)
}else if(m.score1<m.skore){
    addToTeam(m.team1,0,0,1)
    addToTeam(m.team2,1,0,0)
}else{
    addToTeam(m.team1,0,1,0)
    addToTeam(m.team2,0,1,0)
}})

result = Object.values(result)

console.log(result);

结果是

[{"team":"Toronto","wins":2,"draws":0,"losses":1},   
{"team":"Oilers","wins":0,"draws":1,"losses":2},    
{"team":"Rangers","wins":0,"draws":2,"losses":1},    
{"team":"Penguins","wins":2,"draws":1,"losses":0}]
点赞
评论