Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
How to Calculate sum of values from objects insidte nested array

I'm trying to get the Sum of the nested array. The array structure is like this:

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: [] }
]

Here You can see a Question and then a Child array with SubQuestions. And both have a key named weightage. I want to calculate all the weightage values into a sum.

I'm using this approach

  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')

Here I can get the value of weightage from Questions but not from Child Array. Like in the above example of arr. I'm getting sum = 30, but that should be equal to 85, How can I fix this. ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You could take a recursive approach.

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)

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda