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

141
Views
javascript Convierte una matriz de objetos en una sola fila de suma

Quiero sumar todas las filas a una sola fila en la matriz de JavaScript

 var input=[ {id: 'id1', type: "A", active: 3}, {id: 'id2', type: "A", active: 5}, {id: 'id3', type: "B", active: 3}, {id: 'id4', type: "B", active: 4}, {id: 'id5', type: "C", active: 8}, {id: 'id6', type: "C", active: 5}, {id: 'id7', type: "C", active: 6}, {id: 'id8', type: "C", active: 7}, ];

Rendimiento esperado

 [ {id: NaN, type: NaN, active: 41} ] 

 var input=[ {id: 'id1', type: "A", active: 3}, {id: 'id2', type: "A", active: 5}, {id: 'id3', type: "B", active: 3}, {id: 'id4', type: "B", active: 4}, {id: 'id5', type: "C", active: 8}, {id: 'id6', type: "C", active: 5}, {id: 'id7', type: "C", active: 6}, {id: 'id8', type: "C", active: 7}, ]; const t1 = performance.now(); var output=[{}];Object.keys(input[0]).forEach(function(item){ var s=0; input.forEach(function(itema){ s+=parseInt(itema[item]); }); if(!isNaN(s)) output[0][item]=s; else output[0][item]=''; }) const t2 = performance.now(); console.log('output:', output, `in ${t2 - t1}ms`);

¿Hay otra manera más fácil? Gracias por adelantado

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

0

Puede usar reducir a la suma de enteros cada entrada en cada objeto.

 const input = [{"id":"id1","type":"A","active":3},{"id":"id2","type":"A","active":5},{"id":"id3","type":"B","active":3},{"id":"id4","type":"B","active":4},{"id":"id5","type":"C","active":8},{"id":"id6","type":"C","active":5},{"id":"id7","type":"C","active":6},{"id":"id8","type":"C","active":7}]; const t1 = performance.now(); const output = input.reduce((acc, obj) => Object.fromEntries( Object.entries(acc).map(([key, val]) => [ key, parseInt(val, 10) + parseInt(obj[key], 10), ]) ) ); const t2 = performance.now(); console.log(output, `in ${t2 - t1}ms`);

Esto debería funcionar con cualquier estructura de objeto plano, siempre que todos los objetos de la matriz tengan la misma forma.

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!