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

147
Visualizações
flatten array of objects with dynamic keys and sum only values with "_abs" in key name

I have an array of objects that looks like this:

[{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2, ...},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2, ...},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2, ...},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2, ...}]

There can be up to n elements in each object, each one consists of a _perc and an _abs value. I want to reduce the array to only 1 entry and sum each _abs value, the _perc can be anything else, like "-".

An expected result would be:

{"A_abs": 16, "A_perc": "-" "B_abs": 16, "B_perc": "-"  "C_abs": x, "C_perc": "-", ...}

The solution of this question does not fully statisfy me because I don't know how to adapt the function to only sum the "_abs" values.

How to adapt this function to only sum the _abs values, regardles of how many entries the object has?

var data = [{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2},{"A_abs":4,"A_perc":2, "B_abs":4,"B_perc":2}],
    result = data.reduce((r, o) => (Object.entries(o).forEach(([k, v]) => r[k] = (r[k] || 0) + v), r), {});

console.log(result);

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

0

You can check if the key ends with _abs and only if it does you add the values else you simply assign a value of -.

const data = [
    { A_abs: 4, A_perc: 2, B_abs: 4, B_perc: 2 },
    { A_abs: 4, A_perc: 2, B_abs: 4, B_perc: 2 },
    { A_abs: 4, A_perc: 2, B_abs: 4, B_perc: 2 },
    { A_abs: 4, A_perc: 2, B_abs: 4, B_perc: 2 },
  ],
  result = data.reduce(
    (r, o) => (
      Object.entries(o).forEach(([k, v]) =>
        k.endsWith("_abs") ? (r[k] = (r[k] || 0) + v) : (r[k] = "-")
      ),
      r
    ),
    {}
  );

console.log(result);

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