Reputation: 30342
I'm trying to create a function that will return a particular object in an array. I ended up putting a function within the function and not sure if this is clean. Here's the code:
const getTeam = (teams, teamId) => {
if(teamId === 0)
return teams;
const findTeam = (team) => {
return team.teamId === teamId;
}
teams.find(findTeam);
}
And here's the array of teams
[
{
id: 123,
name: "Boston Celtics",
players: [
{ id: 747, name: "John Doe" },
{ id: 749, name: "John Smith" },
]
},
{
id: 234,
name: "LA Lakers",
players: [
{ id: 888, name: "James Smith" },
{ id: 823, name: "John Green" },
]
}
]
My main concern is having the findTeam()
function within getTeam()
function.
UPDATE: Something like this? Maybe?
const getTeam = (teams, teamId) => {
if(teamId === 0)
return teams;
teams.find((team) => {
return team.teamId === teamId;
});
}
Upvotes: 0
Views: 48
Reputation: 1800
This should do it.
function getTeam(teams,teamId) {
return teams.filter((x) => x.id === teamId);
};
Upvotes: 0
Reputation: 138427
getTeam=(teams,teamId)=>teamId?teams.find(team=>team.id==teamId):teams;
Just short not better. As many others noted, anoymous vs. named functions vs. loops will cause a microsecond war, so its not really worth it.
Upvotes: 1