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

152
Vistas
Returning a array of objects by reducing and array

I'm trying to return an array of objects from an array. So for example. I have an array of strings:

const strArr = ["Some", "Thing"];

And I need to return an Array with 2 objects for each position from the strArr, for example:

result:
[{first_key: "Some"}, {second_key: "Some"}, {first_key: "Thing"}, {second_key: "Thing"}]

I have done this, which works, but I rather work without let:

const numeros = ["some", 'thing']
let arr = [];
numeros.map(valor => {
    const titleContains = {
      title_contains: valor,
    }
    const bodyContains = {
      body_contains: valor,
    }
    
    arr.push(titleContains);
    arr.push(bodyContains);
});

console.log(arr)

This code gives me the right result, althought map is being used wrong and I'm have to use a let which I don't want to.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You could take Array#flatMap and return two objects for each value.

const
    data = ["Some", "Thing"],
    result = data.flatMap(valor => [{ first_key: valor }, { second_key: valor }]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

Here's a version with a reduce, you can read more about it here :)

const numeros = ["some", 'thing']
const arr = numeros.reduce((acc, valor) => {
    const titleContains = {
      title_contains: valor,
    }
    const bodyContains = {
      body_contains: valor,
    }
    
    acc.push(titleContains);
    acc.push(bodyContains);
    return acc;
}, []); // <==== note an empty array here.

console.log(arr)

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