1

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?

Itsme
  • 67
  • 4

1 Answers1

2

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);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48