gpt4 book ai didi

javascript - 在嵌套的对象数组中查找数组

转载 作者:行者123 更新时间:2023-12-03 23:01:56 24 4
gpt4 key购买 nike

我想在嵌套的对象数组中找到一个数组,我该怎么做?
这是我的数组

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;
};
它正在工作,但是我这样做的方式看起来很困惑,有什么巧妙的方法可以做到这一点?
谢谢!

最佳答案

您可以使用 flatMap :

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:{}}];

const findTeam = playerId => arr.flatMap(({ teamA, teamB }) => [teamA, teamB])
.find(team => team.some(player => player._id === playerId));

console.log(findTeam('13rfedsc32'));

解释: arr.flatMap(({ teamA, teamB }) => [teamA, teamB])将返回所有比赛中所有球队的数组,无论它们是 AB .然后,您可以轻松找到包含所需播放器的那个。

关于javascript - 在嵌套的对象数组中查找数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65168615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com