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

116
Visualizações
JS: Flatten and Reduce Array of Objects with Multiple Properties and Combine Values

I have been stuck on this for a little while now, but I'm unsure on how I can flatten and reduce the below example data into unique key value pairs with the value being combined if there are multiples of the same key.

Example:

const data = [
  { test: 200 },
  { test2: 300, test3: 100 },
  { test3: 400, test4: 150, test2: 50 },
];

Expected result:

const result = [
    { test: 200 }, 
    { test2: 350 }, 
    { test3: 500 }, 
    { test4: 150 }
];

Any ideas?

TIA

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Try this:

const data = [
  { test: 200 },
  { test2: 300, test3: 100 },
  { test3: 400, test4: 150, test2: 50 }
];

const flattenedAndReduced = data.reduce((prev, current) => {
  Object.keys(prev).forEach((key, index) => {
    if (current[key]) {
      prev[key] += current[key];
      delete current[key];
    }
  });
  Object.keys(current).forEach((key) => {
    if (!prev[key]) prev[key] = current[key];
  });
  return { ...prev };
});

const flattenedAndReducedToArray = Object.keys(flattenedAndReduced).map((key) => ({
  [key]: flattenedAndReduced[key]
}));

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