Estoy tratando de obtener la suma de la matriz anidada. La estructura de la matriz es así:
const arr = [ { question: 'A', parentId: 1, weightage: 10, child: [] }, { question: 'B', parentId: 4, weightage: 0, child: [{ id: 4, sub_question: 'X', weightage: 55 }] }, { question: 'C', parentId: 5, weightage: 20, child: [] } ]Aquí puede ver una pregunta y luego una matriz secundaria con subpreguntas. Y ambos tienen una clave llamada ponderación. Quiero calcular todos los valores de ponderación en una suma.
estoy usando este enfoque
const sum = (value, key) => { if (!value || typeof value !== 'object') return 0 if (Array.isArray(value)) return value.reduce((t, o) => t + sum(o, key), 0) if (key in value) return value[key] return sum(Object.values(value), key) } const weightage = sum(arr, 'weightage')Aquí puedo obtener el valor del peso de las Preguntas pero no de Child Array. Como en el ejemplo anterior de arr. Obtengo suma = 30, pero debería ser igual a 85. ¿Cómo puedo solucionar esto? ?
Podría adoptar un enfoque recursivo.
const sum = (array = [], key) => array.reduce( (total, object) => total + object[key] + sum(object.child, key), 0 ), data = [{ question: 'A', parentId: 1, weightage: 10, child: [] }, { question: 'B', parentId: 4, weightage: 0, child: [{ id: 4, sub_question: 'X', weightage: 55 }] }, { question: 'C', parentId: 5, weightage: 20, child: [] }], result = sum(data, 'weightage'); console.log(result)