我正在尝试创建一个将返回数组中特定对象的函数。我最终在函数中放了一个函数,不确定它是否干净。这是代码:
const getTeam = (teams, teamId) => {
if(teamId === 0)
return teams;
const findTeam = (team) => {
return team.teamId === teamId;
}
teams.find(findTeam);
}
这是一系列球队
[
{
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" },
]
}
]
我主要担心的是findTeam()
函数中的getTeam()
函数。
更新: 像这样的东西?可能?
const getTeam = (teams, teamId) => {
if(teamId === 0)
return teams;
teams.find((team) => {
return team.teamId === teamId;
});
}
答案 0 :(得分:1)
getTeam=(teams,teamId)=>teamId?teams.find(team=>team.id==teamId):teams;
短暂而不是更好。正如许多其他人所指出的那样,无名与命名的函数与循环将导致微秒战争,所以它并不值得。
答案 1 :(得分:0)
这应该这样做。
function getTeam(teams,teamId) {
return teams.filter((x) => x.id === teamId);
};