繁体   English   中英

基于另一个 object 更新对象属性数组

[英]Updating an array of objects properties based on another object

我想根据另一个 object(比赛结果)数组更新 arrays 个对象(联赛表),方法是从两支球队中查找 id 并更新联赛表上的统计数据,

就像足球(足球)联赛表的运作方式一样。

这就是联盟排名的样子

let leagueStandings = [
  {id:'49e93e0d', played: 0, scored: 0, conceded: 0, won: 0, drawn: 0, lost: 0},
  {id:'24e5ddb8', played: 0, scored: 0, conceded: 0, won: 0, drawn: 0, lost: 0}
]

我得到了两支球队的比赛结果对象数组,我需要更新联赛排名。

let matchResult = [
  { id: '49e93e0d', scored: 2, conceded: 1, win: true, draw: false },
  { id: '24e5ddb8', scored: 1, conceded: 2, win: false, draw: false }
]

所以我想出了这段代码

function updateStandings(match) {
    let team;
    match.forEach(prop => { //loop both teams in result and update their respective stats
        team = leagueStandings.find(team => team.id === prop.id); // find the team to update by id
        team.played++
        team.scored += prop.scored
        team.conceded += prop.conceded
        team.goalDifference += (prop.scored - prop.conceded)
        if (prop.win) team.won++
        if (prop.draw) team.drawn++
        if (!prop.win && !prop.draw) team.lost++
    });
}

updateStandings(matchResult)

// outputs the expected the result
[
  { id: '49e93e0d', played: 1, scored: 2, conceded: 1, won: 1, drawn: 0, lost: 0 },
  { id: '24e5ddb8', played: 1, scored: 1, conceded: 2, won: 0, drawn: 0, lost: 1 }
]

哪个确实有效并且可以完成工作,但是我认为有更好的方法吗? 联赛排名数组也将包含大量球队,所以我不确定这是否是最好的方式?

预计 output

[
  { id: '49e93e0d', played: 1, scored: 2, conceded: 1, won: 1, drawn: 0, lost: 0 },
  { id: '24e5ddb8', played: 1, scored: 1, conceded: 2, won: 0, drawn: 0, lost: 1 }
]

完整代码在这里

您解决方案中的find() function 将通过每个leagueStandings项目匹配id go

因为leagueStandings平均来说是无序的,所以它必须循环遍历一半的项目才能找到匹配项。

这可以通过 ID 索引来解决

考虑将此结构用于leagueStandings

let leagueStandings = {
  '49e93e0d': {played: 0, scored: 0, conceded: 0, won: 0, drawn: 0, lost: 0},
  '24e5ddb8': {played: 0, scored: 0, conceded: 0, won: 0, drawn: 0, lost: 0}
}

现在您可以更改此行:

team = leagueStandings.find(team => team.id === prop.id);

对此:

team = leagueStandings[prop.id];

并进行索引查找

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM