I want to find an array inside a nested array of objects, how can I do that?
Here is my array
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": {}
}
];
now I want to create a function that returns me the array of the team that a player is in by the _id
for example, I created this:
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;
};
and it's working, but the way I did it looks very messy, there is any neat way to do that? Thanks!
asked Dec 6, 2020 at 13:29
Asaf
1,2652 gold badges17 silver badges19 bronze badges
-
1does every object of array has only two teams - teamA & teamB?michael– michael2020年12月06日 13:31:50 +00:00Commented Dec 6, 2020 at 13:31
-
@baymax yes correctAsaf– Asaf2020年12月06日 17:00:27 +00:00Commented Dec 6, 2020 at 17:00
1 Answer 1
You can use 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'));
Explanation:
arr.flatMap(({ teamA, teamB }) => [teamA, teamB]) will return an Array of all teams from all matches, regardless of them being A or B. You can then easily find the one which contains the wanted player.
answered Dec 6, 2020 at 13:38
blex
25.7k6 gold badges49 silver badges78 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js