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

86
Visualizações
Merge values to an array based on similar object key javascript

i have a return like this

[
{
    "tripw3": "1"
},
{
    "tripw1": "2"
},
{
    "tripw1": "3"
},
{
    "tripw2": "4"
},
{
    "tripw2": "5"
},
{
    "tripw3": "6"
},
{
    "tripw3": "7"
}]

and I want to make the above result be

[
{
 tripw3: ["1", "6", "7"],
 tripw2: ["4", "5"],
 tripw1: ["3", "2"]
}]

Until now I'm still confused to make this happen.

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

You cane easily acheve the result using reduce, Object.keys and forEach

const arr = [
  {
    tripw4: "1",
  },
  {
    tripw4: "2",
  },
  {
    tripw4: "3",
  },
  {
    tripw4: "4",
  },
  {
    tripw4: "5",
  },
  {
    tripw4: "6",
  },
  {
    tripw4: "7",
  },
];

const result = [arr.reduce((acc, curr) => {
  Object.keys(curr).forEach((k) => acc[k] ? acc[k].push(curr[k]) : (acc[k] = [curr[k]]));
  return acc;
}, {})];

console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Santiago Gelvez 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