Home > Blockchain >  JS array recursion for unknown number of objects
JS array recursion for unknown number of objects

Time:03-21

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?

CodePudding user response:

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;
}
  • Related