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

127
Vistas
.map equivalent of .forEach to create an object

The following code populates an object called result with the values in keys as the keys and an empty string as each key's value. This is working as desired.

const keys = ['one', 'two', 'three'];
const result = {};
keys.forEach(key => {
  result[key] = '';
});
console.log(result);

enter image description here

However, I'm wondering if the result object can be created in a single command by using .map. Below is what I've tried but it yields an array of objects rather than a single object.

const result = keys.map(key => ({
  [key]: ''
}));
console.log(result);

enter image description here

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

0

You can combine Object.fromEntries and map methods. With map you can get array of [key, value] pairs and then by calling fromEntries you get an object from that array.

const keys = ['one', 'two', 'three'];
const result = Object.fromEntries(keys.map(k => ([k, ''])))
console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Here's an alternative approach that only needs one method. (Array.prototype.reduce())

const keys = ["one", "two", "three"];

const result = keys.reduce((a, c) => ({ ...a, [c]: "" }), {});
console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar

0

you can use your map, then reduce:

keys
  .map(k => ({[k]: ""}))
  .reduce((x, r) => ({...x, ...r}), {})
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