Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

137
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda