Asaf
Asaf

Reputation: 1261

find array in nested array of objects

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!

Upvotes: 4

Views: 81

Answers (1)

blex
blex

Reputation: 25634

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.

Upvotes: 4

Related Questions