Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda