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

155
Vistas
Sum array of objects with dynamic keys - Javascript

I've got the following array

arr = [
  { 'Atencion Personalizada': 2, 'Caja': 3 },
  { 'Atencion Personalizada': 1 },
  { 'Tarifa Social': 3 }
]

Expected output: 9

And I would like to sum the properties the shortest way possible. The thing is that the object keys are always variable so i can't go for:

arr.reduce((acc,item) => acc+item.keyName)

Found this post but can't adapt the code to my solution either:

var data = [{ A: 4, B: 2 }, { A: 2, B: 1 }, { A: 3, B: 1 }, { A: 2, B: 1, C: 1 }],
    result = data.reduce((r, o) => (Object.entries(o).forEach(([k, v]) => r[k] = (r[k] || 0) + v), r), {});

Thank you in advance

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

0

Here's my solution. Map through the array and flatten the properties values, then reduce them.

const arr = [
  { 'Atencion Personalizada': 2, 'Caja': 3 },
  { 'Atencion Personalizada': 1 },
  { 'Tarifa Social': 3 }
]

console.log(arr.flatMap(e => Object.values(e)).reduce((a, b) => a + b));

about 4 years ago · Juan Pablo Isaza Denunciar

0

Use reduce twice, once on the outer array and once on the values of each object inside it.

const arr = [
  { 'Atencion Personalizada': 2, 'Caja': 3 },
  { 'Atencion Personalizada': 1 },
  { 'Tarifa Social': 3 }
];
const total = arr.reduce((gt, item) => 
  gt + Object.values(item).reduce((t, sub) => t + sub, 0)
, 0);

console.log(total);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Maybe something like this?

let acc = {};
for (let o of arr) for (let key in o) {
    acc[key] ??= 0;
    acc[key] += o[key];
}

Not a one-liner though

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