Home > other >  Create new JSON string from array
Create new JSON string from array

Time:10-18

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.

CodePudding user response:

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

CodePudding user response:

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

This should do the trick:

let rolesArray = ['Role1', 'Role2', 'Role3']; 
let rolesObject = {};

// iterate over roles to fill an object 
rolesArray.forEach((role) => {
    rolesObject[role] = true; 
});

JSON.stringify(rolesObject) // Outputs the desired string

Or in a more concise way but less readable for a SO example :

JSON.stringify(rolesArray.reduce((o, s) => { o[s] = true; return o }, {}));

CodePudding user response:

I have a preference for using the for-loop — still valid but other methods will be much short.

var array = ["Role1", "Role2", "Role3"],
  json = {};
for (i = 0; i < array.length; i  ) {
  json[array[i]] = true;
}
console.log(json);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Use reduce() so we can set the value to true without a second loop

Using the spread operator (...) to merge the objects

const data = ['Role1', 'Role2', 'Role3'];
const obj = data.reduce((prev, cur) => ({ ...prev, [cur]: true }), {});

console.log(obj);
console.log(JSON.stringify(obj));
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

if you want to do that you must this code Below .

json-encode(Array)

  • Related