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
12
  • 1
    Is the space before the first true in the expected output deliberate/required? Commented May 28, 2019 at 7:57
  • 2
    What have you tried to achieve this? Is the output a string? Commented May 28, 2019 at 7:57
  • @CertainPerformance am sorry ,space is not deliberate Commented May 28, 2019 at 7:58
  • 1
    It's either an object, or a string/text in JSON format. There's no such thing as a "JSON object". You can use Object.keys(myObj) to get an array of keys., then use .map to create a new array. There's also .join(). Commented May 28, 2019 at 7:59
  • 1
    Your JSON is invalid - keys need to be surrounded in "s, best to fix that, and then you can turn it into an object with JSON.parse Commented May 28, 2019 at 8:00

3 Answers 3

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);

Sign up to request clarification or add additional context in comments.

Comments

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(', '))

Comments

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())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.