javascript如何替换ID匹配的数据

zf2sa74q  于 2023-01-16  发布在  Java
关注(0)|答案(3)|浏览(114)

我在数组中有一个这样的数据。

[
        {
            "teamName": "TeamA",
            "players": ["1","2"]
        },
        {
            "teamName": "TeamB",
            "players": ["2"]
        }
        
]

我想替换在其他数组中匹配的球员id

players = [
          {
            "id": "1",
            "playername": "alex"

          },
          {
            "id": "2",
            "playername": "john"
          }
]

所以输出会是这样的

[
        {
            "teamName": "TeamA",
            "players": [
          {
            "id": "1",
            "playername": "alex"         
          },
          {
            "id": "2",
            "playername": "john"
          }]
        },
        {
            "teamName": "TeamB",
            "players": [
          {
            "id": "2",
            "playername": "john"
          }]
        }
        
]

我试着用for循环来查找,以及它将在哪里查找和替换,但这对我不起作用。

3wabscal

3wabscal1#

你可以通过迭代第一个数组并更新该数组中每个元素的players属性来实现这一点。

let arrOne = [
        {
            "teamName": "TeamA",
            "players": ["1","2"]
        },
        {
            "teamName": "TeamB",
            "players": ["2"]
        }
        
]
players = [
          {
            "id": "1",
            "playername": "alex"

          },
          {
            "id": "2",
            "playername": "john"
          }
]

// solution 

arrOne.forEach( teamObject => { 
    let newPlayerArray = [];
    teamObject.players.forEach( id => {
        let newPlayerObject = {};
        newPlayerObject.id = id;
        newPlayerObject.playername = players.find( player => player.id == id)?.playername;
        newPlayerArray.push(newPlayerObject)
    }) 
    teamObject.players = newPlayerArray;
})
nimxete2

nimxete22#

一种方法是:

// defining the variables, naming 'teams' as it was unnamed in
// the original post:
let teams = [
    {
      "teamName": "TeamA",
      "players": ["1", "2"]
    },
    {
      "teamName": "TeamB",
      "players": ["2"]
    }
  ],
  // updated the name of this Array of Objects due to the naming
  // clash between the original name ('players') when using
  // destructuring assignments while iterating the 'teams' Array,
  // because of an identically-named property:
  playerDetails = [{
      "id": "1",
      // I updated this property-name to use camelCase consistently:
      "playerName": "alex"

    },
    {
      "id": "2",
      "playerName": "john"
    }
  ],
  // rather than editing the original Array, we create a new one
  // by iterating over the teams Array, using Array.prototype.map():
  combined = teams.map(
    // using destructuring assignement to retrieve the named properties
    // of the Object passed in to the function:
    ({
      teamName,
      players
    }) => {
      // because we're returning an Object literal, we have to use return and wrap
      // the anonymous callback function of the Arrow function in curly braces ('{...}')
      // to avoid the returned Object-literal being misinterpreted as a function body:
      return {
        // we return the teamName property unchanged:
        teamName,
        // but here we update the players property, we iterate over the players Array,
        // again using players.prototype.map() to update the existing Array based on the
        // result of actions taken in the anonymous Arrow function:
        players: players.map(
          // we pass in a reference to the 'id' enclosed within the player Array,
          // giving it a verbose/clear name given that 'id' would be a sensible/short
          // name, but is used within the enclosed function as the named property of
          // the other function we're working with.
          // within the anonymous function we use Array.prototype.find():
          (teams_playerID) => playerDetails.find(({
          // passing in a reference to the 'id' property-name of the Object
          // within the playerDetails Array:
            id
          // and here we check to see if the 'id' of the playerDetails Array is
          // exactly-equal to the teams_playerID variable; if so this Object is
          // returned and the 'players' Array is updated, and changed from a String
          // to the found Object; if no match is found the current 'players' Array-value
          // is unchanged:
          }) =>  id == teams_playerID ))
      }
    });

console.log(combined);
// [{"teamName":"TeamA","players":[{"id":"1","playerName":"alex"},{"id":"2","playerName":"john"}]},{"teamName":"TeamB","players":[{"id":"2","playerName":"john"}]}]

JS Fiddle demo.
参考文献:

vwkv1x7d

vwkv1x7d3#

构建结果的方法是遍历球队列表,按id查找每个球员,然后将球员记录添加到结果的球员数组中。

const teams = [
    {
        "teamName": "TeamA",
        "players": ["1", "2"]
    },
    {
        "teamName": "TeamB",
        "players": ["2"]
    }
]
const players = [
    {
        "id": "1",
        "playername": "alex"
    },
    {
        "id": "2",
        "playername": "john"
    }
]
let result = []
teams.forEach(team => {
    let record = {
        "teamname": team.teamName,
        "players": []
    }
    team.players.forEach(player_id => {
        record.players.push(players.find(p => p.id === player_id))
    })
    result.push(record)
})
console.log(JSON.stringify(result, null, 4))

相关问题