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

113
Views
JS array recursion for unknown number of objects

I have an Object with nested objects in JS and there's an Object with array that has the same name and can pop up multiple times with different values. I just want to sum the length of each array always going one level deeper till this object is missing.

for example:

0 : {id: 1, importantObject: {id: 1, {importantObject: {id: 1, importantObject:{...},}, somethingElse: 23}, something: 'test'}

1 : {id: 2, importantObject: {id: 24, {importantObject: {id: 55, importantObject:{...},}, somethingElse: 92}, something: 'test'}

and so on..

I've tried to do the following:

const getCount = (a) => {
    let count = 0;
    a.map((b) => {
      if (b.importantObject) {
        count += b.importantObject.length;
        getCount(b.importantObject)
      }
    });
     return count;
  }

However, I don't get the correct count. What am I doing wrong?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

when doing recursion you must use recursive call return value

const getCount = (a) => {
  let count = 0;
  for (let b of a) {
    if (b.importantObject) {
      count += b.importantObject.length;
      count += getCount(b.importantObject); // here
    }
  }
  return count;
}
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!