我想通过查找两支球队的 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 }
]
哪个确实有效并且可以完成工作,但是我认为有更好的方法来做到这一点?而且联赛积分榜数组将包含大量球队,所以我不确定这是否是最好的方法?
预期输出
[
{ 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 }
]
完整代码HERE
最佳答案
解决方案中的 find()
函数将遍历每个 leagueStandings
项目以匹配 id
因为 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];
并进行索引查找
关于javascript - 根据另一个对象更新对象属性数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71250280/