Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
Cómo calcular la suma de valores de objetos dentro de una matriz anidada

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? ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!