拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 在vue.js中加入具有相同栏位名称的2个物件

在vue.js中加入具有相同栏位名称的2个物件

白鹭 - 2022-02-25 2108 0 0

我试图通过键连接 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热心网友回复:

名称正在被替换,因为PlayerTeam物件都有一个name属性,并且解决方案会覆写namewhile 组合物件。

由于您想分别访问team物件idname使用team.idteam.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 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *