0

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?

2
  • I'll be helpful if you can share the exact input data. Commented Mar 21, 2022 at 9:58
  • Please do not use .map() for simple array iteration. Use .forEach() or a normal loop to do that. Commented Mar 21, 2022 at 10:08

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I didn't know that I should also call recursively call the return value. Thanks!

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.