Tengo un Objeto con objetos anidados en JS y hay un Objeto con matriz que tiene el mismo nombre y puede aparecer varias veces con diferentes valores. Solo quiero sumar la longitud de cada matriz siempre yendo un nivel más profundo hasta que falte este objeto.
por ejemplo:
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'}
y así..
He intentado hacer lo siguiente:
const getCount = (a) => { let count = 0; a.map((b) => { if (b.importantObject) { count += b.importantObject.length; getCount(b.importantObject) } }); return count; }Sin embargo, no obtengo el conteo correcto. ¿Qué estoy haciendo mal?
al hacer la recursividad, debe usar el valor de retorno de la llamada recursiva
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; }