Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
Angular typescript how to flatten nested array to find only object with certain condition

I have the following array object. I would like to flatten the array to get only object with names containing 'Martin'

Source Array:

[
    {
        "id": 302,
        "name": "David Martin",
        "subordinates": [
            {
                "id": 265,
                "name": "Martin Regan",
            },
            {
                "id": 300,
                "name": "William Baker",
            },
            {
                "id": 301,
                "name": "Anthony Mazzarino",
                "subordinates": [
                    {
                        "id": 11245,
                        "name": "Martin Lozano",
                    }
                ]
            }
        ]
    },
    {
        "id": 10441,
        "name": "Martin Delage De Luget"    
    }
]

Expected Result:

[
    {
        "id": 302,
        "userGuid": "66d6fd24-0e22-4384-9181-f72c4e81cefd",
        "name": "David Martin"  
    },
    {
        "id": 265,
        "name": "Martin Regan",
    },
    {
        "id": 11245,
        "name": "Martin Lozano",
    }   
]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Recursion is always an easy solution in these kind of cases:

flatElements = (array, keyword) => {

  // Recursive function
  const traverse = (subArray, acc = []) => {

    subArray.forEach(element => {

      const {id, name, subordinates} = element;

      // If object with certain condition push it in the resulting acc 
      if (element.name.contains(keyword)) {
        acc.push({id, name});
      }

      // If subordinates exist, traverse them deeply
      if (subordinates) {
          traverse(subordinates, acc);
      }

    });

    // Return accumulator
    return acc;

  }
  
  return traverse(array, []);
  
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!