show dynamic select items mapping over array of objects

pet*_*gan 3 javascript ecmascript-6 reactjs

I have an array that looks like this:

const teamsAndPlayers = [
    {
        team: 'Liverpool',
        players: ['Salah', 'Henderson']
    },
    {
        team: 'Man Utd',
        players: ['Rashford', 'De Gea']
    },
    {
        team: 'Chelsea',
        players: ['Hazard', 'Willian']
    }
];
Run Code Online (Sandbox Code Playgroud)

I have 2 select boxes, the second of which is dynamic based on what the user selects. The issue I am having is that I am not sure the best way to find the related array based on the user choice. I know I could use find and other methods, but is there anyway I can do it all in the map function in the return statement?

My code looks like the following:

const Menu = () => {

   const [selectedTeam, setSelectedTeam] = useState(null);

   return (
      <div>
        <select 
           onChange={e => setSelectedTeam(e.target.value)} 
           id="team" 
           name="team"
        >
         {teamsAndPlayers(item => (
            <option key={item.team} value={item.team}>
               {item.team}
            </option>
        ))}

        <select id="players" name="players">
         {teamsAndPlayers(item => (
            // how can I get the related players in here 
            // based on first select choice?
        ))}

      </div>
   )
}
Run Code Online (Sandbox Code Playgroud)

kni*_*ton 6

我将使用对象而不是数组来定义选择的输入(如果您确实想避免使用find)。因此,teamsAndPlayers将如下所示:

const teamsAndPlayers = {
  liverpool: {
    name: 'Liverpool',
    players: ['Salah', 'Henderson']
  },
  manUtd: {
    name: 'Man Utd',
    players: ['Rashford', 'De Gea']
  },
  chelsea: {
    name: 'Chelsea',
    players: ['Hazard', 'Willian']
  }
};
Run Code Online (Sandbox Code Playgroud)

然后,在fisrt select中的选项将如下所示:

{Object.keys(teamsAndPlayers).map(key => (
  <option key={key} value={key}>
    {teamsAndPlayers[key].name}
  </option>
))}
Run Code Online (Sandbox Code Playgroud)

然后,第二个选择中的选项将如下所示:

{teamsAndPlayers[selectedTeam].players.map(player => (
  <option key={player} value={player}>
    {player}
  </option>
))}
Run Code Online (Sandbox Code Playgroud)