4

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!

2
  • 1
    does every object of array has only two teams - teamA & teamB? Commented Dec 6, 2020 at 13:31
  • @baymax yes correct Commented Dec 6, 2020 at 17:00

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.