'String into JSON Format

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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Majed Badawi