How can I dynamically convert a json object to the following manner I do have
{ eligible: true, qualified:true }
but I need to make it like this
eligible= true, qualified=true
How can I dynamically convert a json object to the following manner I do have
{ eligible: true, qualified:true }
but I need to make it like this
eligible= true, qualified=true
You can use Object.entries to get a two dimensional array of object and then use Array.prototype.map to join the array element (key, value) with an =
.
Finally join the array with a ,
to get the expected output.
var x = { eligible: true, qualified:true };
var newX = Object.entries(x).map(el => el.join("=")).join(", ");
console.log(newX);
If we can assume the string is a valid JSON object (yours is missing the quotes) you can parse the string as JSON and then use Object.entries
to get the key value pairs which can then be mapped and joined down to your desired string output.
const jsonStr = '{ "eligible": true, "qualified":true }'
const jsonObj = JSON.parse(jsonStr)
console.log(Object.entries(jsonObj).map(e => e.join('=')).join(', '))
You can get entries of object and change the key/value
to string using reduce
let obj = { eligible: true, qualified:true }
let str = Object.entries(obj).reduce((op,[key,value],index,arr)=>{
op+= `${key}=${value}${index !== arr.length-1 ? ',' : ''} `
return op
},'')
console.log(str.trim())