How to pass a parameter inside of an optionalChain

Viewed 39

I have a function where I get the id of the desired team depending on whether it is home or away team. Instead of creating separate functions for both actions I wanted to do it in one go. Here is what I have so far :

 const getTeamLogo = (team) => {
    let teamStatus = team === "home" ? "homeTeam" : "awayTeam";
    let teamId = nextMatch?.teamStatus.id
    let ourTeam = teamInfo?.find(({ team }) => team.id === teamId);
    return ourTeam?.team.crestUrl;
  };

To extract the id I need to pass either homeTeam or awayTeam. Therefore I have thought of creating another variable so that depending of the parameter I could pass desired word there but with the current situation I do get Cannot read property 'id' of undefined error. Any idea on how would I improve this code and get the desired result? Thanks in advance.

1 Answers

Use teamStatus as a computed key.

const getTeamLogo = (team) => {
  let teamStatus = team === "home" ? "homeTeam" : "awayTeam";
  let teamId = nextMatch?.[teamStatus]?.id
  let ourTeam = teamInfo?.find(({ team }) => team.id === teamId);
  return ourTeam?.team.crestUrl;
};
Related