Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

191
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda