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

192
Visualizações
Return different objects using map without pushing into array

The following code in JavaScript:

const mixedObjects = [1,2,3].map(num => {
    return { a: 'always same' }
});

returns the following result:

[
  {a: 'always same'},
  {a: 'always same'},
  {a: 'always same'}
]

I want to return the following without declaring an empty array outside and then pushing into it. So do it all inside the map. Is this possible?

What I want to return:

[
  {a: 'always same'},
  {b: 1},
  {a: 'always same'},
  {b: 2},
  {a: 'always same'},
  {b: 3}
]
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Use Array.flatMap(), and return a tuple of the 2 objects on each iteration. The flatMap would create a flattened array of objects.

const mixedObjects = [1,2,3].flatMap(b => {
  return [{ a: 'always same' }, { b }]
});

console.log(mixedObjects);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can combine map and flat methods:

const mixedObjects = [1,2,3].map(num => {
    return [{ a: 'always same' }, {b: num}];
}).flat();

P. S. Or use flatMap method as suggested by Ori Drori.

about 4 years ago · Juan Pablo Isaza Relatório

0

... reduce based solutions work as well ...

console.log(
  [1,2,3].reduce((result, b) =>
    [...result, { a: 'always same' }, { b }] , []
  )
);
console.log(
  [1,2,3].reduce((result, b) =>
    result.concat({ a: 'always same' }, { b }), []
  )
);
console.log(
  [1,2,3].reduce((result, b) => {
  
    result.push({ a: 'always same' }, { b });
    return result;

  }, [])
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

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