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

433
Visualizações
array.reduce() but need to set a key for the return value

I have an array where I am using .reduce to group all the matching ids of the array into new array with the id.

The problem is that my output looks like this


[
  {
    CHb5591f5db2a546d3af: [ [Object], [Object] ],
    CH5e86016c8b894d9d87: [ [Object], [Object], [Object], [Object], [Object], [Object] ]
  }
]

I need to have the output like this

[
  
    {id: CHb5591f5db2a546d3af, content: [ [Object], [Object] ]},
    {id: CH5e86016c8b894d9d87, content: [ [Object], [Object], [Object], [Object], [Object], [Object] ]}
  
]

Here is my attempt at the reducer function

result = await response.reduce(function (a, i) {
        a[i.messagesId] = a[i.messagesId] || []; //it generates a new property i.messagesId with an array if it does not exist (the value of not existing properties is undefined). if exist, it assign itself 
        a[i.messagesId].push(i);
        return a;
    }, Object.create({}));
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If there is single object inside array then you can easily achieve using Object.entries()

For demo purposes, I've used "object" as a string

const arr = [
  {
    CHb5591f5db2a546d3af: [["Object"], ["Object"]],
    CH5e86016c8b894d9d87: [
      ["Object"],
      ["Object"],
      ["Object"],
      ["Object"],
      ["Object"],
      ["Object"],
    ],
  },
];

const result = Object.entries(arr[0]).map(([id, content]) => ({ id, content }));
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

May be this is what you're looking for. We have a Array.prototype.reduce() method that returns our desired object array.

const array = [
      {
        'CHb5591f5db2a546d3af':
          [
            { animal: 'Cat', name: 'Tom' },
            { animal: 'Dog', name: 'Bruno' }
          ]
      },
      {
        'CH5e86016c8b894d9d87':
          [
            { animal: 'Alligator', name: 'Mike' }
          ]
      },
      {
        'CH5e86016c8b894d9d97':
          undefined
      }
    ]

    const reducer = function (acc, item) {
      for (const _key in item) {
        acc.push({
          'id': _key,
          'content': item[_key]
        })
      }
      return acc;
    }
    console.log(array.reduce(reducer, []))

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