Home > Back-end >  String into JSON Format
String into JSON Format

Time:04-17

Need one help.

I have two strings in two different variables;

var var1 = "Myname";

var var2 = "Myage";

var jsonObj = ?

console.log(jsonObj);

I would like to have the console output of "jsonObj" into a JSON object(not a key value pair) created from these strings in the below format;

{"Myname":"Myage"}

Please let me know how can achieve this?

CodePudding user response:

You can use computed property names and JSON.stringify

const var1 = "Myname", var2 = "Myage";

const jsonObj = { [var1]: var2 };

const res = JSON.stringify(jsonObj);

console.log(res);

  • Related