我试图通过键连接 2 个物件,这些物件中有 2 个具有相同名称但具有不同值的栏位。
var players = [{ id : 'a', name : "player1",team:1},{ id : 'b', name : "player2",team:1}, { id : 'c', name : "player3",team:2}]
var teams = [{ id : 1, name : "LA"}, {id : 2, name: "IL"}]
我希望能够得到类似的结果:
var mergedList = [{ id : 'a', name : "player1",team.id:1, team.name: "LA"},
{ id : 'b', name : "player2",team__id:1, team_name: "LA"},
{ id : 'c', name : "player3",team__id:2, team_name: "US"}]
这是我到目前为止尝试过的:
const mergedList = players.map((player) => ({
...player,
...teams.find((team) => team__id === player_team),
}));
但是来自球员的姓名栏位被球队提交的姓名所取代。
uj5u.com热心网友回复:
您需要为 中的栏位设定新的属性键teams
。请记住,密钥不允许包含.
const mergedList = players.map((player) => {
const team = teams.find((team) => team.id === player.team);
return {
...player,
team_id: team?.id,
team_name: team?.name,
}
});
uj5u.com热心网友回复:
team.id
并且team.name
是无效的键。您可以team
使用所需的物件设定键
const players = [{ id : 'a', name : "player1",team:1},{ id : 'b', name : "player2",team:1}, { id : 'c', name : "player3",team:2}];
const teams = [{ id : 1, name : "LA"}, {id : 2, name: "IL"}];
const mergedList = players.map((player) => ({
...player,
team: teams.find((team) => team.id === player.team)
}));
console.log(mergedList)
uj5u.com热心网友回复:
名称正在被替换,因为Player
和Team
物件都有一个name
属性,并且解决方案会覆写name
while 组合物件。
由于您想分别访问team
物件id
和name
使用team.id
和team.name
,一个合适的解决方案可能是在玩家物件中放置团队物件,例如:
var players = [{ id : 'a', name : "player1",team:1},{ id : 'b', name : "player2",team:1}, { id : 'c', name : "player3",team:2}]
var teams = [{ id : 1, name : "LA"}, {id : 2, name: "IL"}]
const mergedList = players.map((player) => ({
...player,
team: teams.find((team) => team.id === player.team),
}));
mergedList.forEach(ele => {
console.log(`${ele.id}, ${ele.name} is in team ${ele.team.id}, ${ele.team.name}`);
});
0 评论