0

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
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
midhun k
  • 546
  • 1
  • 12
  • 28

3 Answers3

6

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);
void
  • 36,090
  • 8
  • 62
  • 107
2

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(', '))
James Coyle
  • 9,922
  • 1
  • 40
  • 48
1

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())
Code Maniac
  • 37,143
  • 5
  • 39
  • 60