Home > Software engineering >  join 2 objects with the same field name in vue.js
join 2 objects with the same field name in vue.js

Time:12-28

I'm trying to join 2 object by key, with 2 fields with the same name in these objects, but with different values.

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"}]

I want to be able to end up with something like:

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"}]

Here is what I tried so far:

const mergedList = players.map((player) => ({
        ...player,
        ...teams.find((team) => team__id === player_team),
      }));

But the name field from players is replaced by the name filed from teams.

CodePudding user response:

You need to set new property keys for the fields from teams. And remember that the key is not allowed to include the .

const mergedList = players.map((player) => {
    const team = teams.find((team) => team.id === player.team);
    return {
        ...player,
        team_id: team?.id,
        team_name: team?.name,
    }
});

CodePudding user response:

team.id and team.name are invalid keys. You can set key team with needed object

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)

CodePudding user response:

The name is getting replaced because both Player and Team objects have a name property and the solution overwrites the name while combining the objects.

Since you want to access team object's id and name using team.id and team.name respectively, one suitable solution could be to have the team object inside the player object, something like :

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}`);
});

  • Related