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

136
Vistas
Create new JSON string from array

Fairly new to JSON and I'm trying to get my head around conversions. I have an array:

['Role1', 'Role2', 'Role3']

and I'm trying to stringify it so that it reads as

{"Role1": true, "Role2": true, "Role3": true}

So far I've tried assigning the original array to an object and the calling stringify but I can't figure out how to add the boolean value in the string. Thanks in advance.

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

0

You'll have to create an intermediate reduce function to assign those values before converting to JSON.

const data = ['Role1', 'Role2', 'Role3']

const makeJson = () =>
  JSON.stringify(data.reduce((a, c) => ({ ...a, [c]: true }), {}))

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

about 4 years ago · Juan Pablo Isaza Denunciar

0

Is this what you need as output?

const arr = ['Role1', 'Role2', 'Role3']

const result = JSON.stringify(arr.reduce((a, n)=>{
    return {
        ...a,
        [n]: new Boolean(true).toString()    
    }
},{}))
console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Another approach could be to combine Object.fromEntries with Array.prototype.map

const data = ['Role1', 'Role2', 'Role3']

const result = Object.fromEntries(data.map(s => [s, true]));

console.log(JSON.stringify(result));

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