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

221
Vistas
JavaScript, how to create an object out of an array?

I would like to convert an array that looks like this:

['foo', 'bar', 'baz']

to an object that looks like this:

{
  foo: true,
  bar: true,
  baz: true,
}

In most languages you would have some form of fill(keys, value) function:

var array = ['foo', 'bar', 'baz'];
var object = fill(array, true);
// object = { foo: true, bar: true, baz: true}

But in JS I can only find one for numeric keys using a range, not a list of keys. Is there a fill function that will do exactly that?

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

0

Try this:

const data = ['foo', 'bar', 'baz']
const asObject = Object.fromEntries(data.map(d => ([d, true])))

console.log(asObject)
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can build an object with .reduce():

var object = array.reduce((o, e) => (o[e] = true, o), {});

edit — or the clever Object.fromEntries() solution mentioned in a comment.

about 4 years ago · Juan Pablo Isaza Denunciar

0

There isn't such function as fill(keys, value) that you mentioned, but you could also do so:

let tab = ['foo', 'bar', 'baz'];

let obj = {}

tab.forEach(v=>{obj[v]=true});

console.log(obj)

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