Search code examples
javascriptobject

I want to make Javascript object dynamic


Here is Code

var str = "Value1";

var str1 = "Value2";

var obj = {
  [str]: str1
};

console.log(obj);

I am getting obj as

{
    Value1:"Value2"
}

But I want this object as

{
    "Value1":"Value 2"
}

Can any one explain how it is possible?


Solution

  • At first your code: var obj = {["Value1"]: "Value2"}; is wrong. You have to write: var obj = {"Value1": "Value2"}; or var obj = {Value1: "Value2"};.

    And then if I understood you correctly: in your comment you wrote:

    I wana get Value1 in double quotes too dynamic means I want dynamic index too in double quotes

    The answer:

    Object {Value1:"Value2"} is the same like {"Value1":"Value2"}. The difference is to see in displaying (spelling, writing) of your code only.

    For example you will not see the difference if you execute following code:

    var myObj1 = {"Value1":"Value2"};
    var myObj2 = {Value1:"Value2"};
    
    console.log(myObj1.Value1); //Value2
    console.log(myObj2.Value1); //Value2
    
    console.log(myObj1["Value1"]); //Value2
    console.log(myObj2["Value1"]); //Value2
    
    console.log(JSON.stringify(myObj1)); //{"Value1":"Value2"}
    console.log(JSON.stringify(myObj2)); //{"Value1":"Value2"}