David
David

Reputation: 891

join 2 objects with the same field name in vue.js

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.

Upvotes: 0

Views: 236

Answers (2)

Tyler Durden
Tyler Durden

Reputation: 1070

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

Upvotes: 0

Kien Nguyen
Kien Nguyen

Reputation: 2701

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

Upvotes: 1

Related Questions