Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

135
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!