我想在嵌套的对象数组中查找一个数组,该怎么做?
这是我的数组:
const arr = [
{
"teamA": [
{
"_id": "5fcb57c5a1a426c03bcfd25f",
"level": 10,
"username": "asaf"
}
],
"teamB": [],
"options": {}
},
{
"teamA": [
{
"_id": "a7fgy3h1uio",
"level": 10,
"username": "asaf"
}
],
"teamB": [
{
"_id": "13rfedsc32",
"level": 10,
"username": "asaf"
},
{
"_id": "dghg453r3q",
"level": 10,
"username": "asaf"
}
],
"options": {}
}
];
现在我想创建一个函数,通过 _id 返回球员所在队伍的数组。
例如,我创建了以下代码:
const findTeam = playerId => {
const match = arr.find(({ teamA, teamB }) => [teamA, teamB].some(team => team.some(i => i._id == playerId)));
if(!match) return;
const { teamA, teamB } = match;
const team = [teamA, teamB].find(team => team.some(i => i._id == playerId));
return team;
};
我的代码现在可以运行,但是我写的方式看起来很凌乱,有没有更好的方法呢? 谢谢!