create object using variables for property name [duplicate]












71
















This question already has an answer here:




  • How to use a variable for a key in a JavaScript object literal?

    11 answers




Is it at all possible to use variable names in object literal properties for object creation?



Example



function createJSON (propertyName){
return { propertyName : "Value"};
}

var myObject = createJSON("myProperty");

console.log(myObject.popertyName); // prints "value"
console.log(myObject.myProperty); // Does not exist









share|improve this question















marked as duplicate by Bergi javascript
Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Jan 11 '16 at 18:32


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.























    71
















    This question already has an answer here:




    • How to use a variable for a key in a JavaScript object literal?

      11 answers




    Is it at all possible to use variable names in object literal properties for object creation?



    Example



    function createJSON (propertyName){
    return { propertyName : "Value"};
    }

    var myObject = createJSON("myProperty");

    console.log(myObject.popertyName); // prints "value"
    console.log(myObject.myProperty); // Does not exist









    share|improve this question















    marked as duplicate by Bergi javascript
    Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

    StackExchange.ready(function() {
    if (StackExchange.options.isMobile) return;

    $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
    var $hover = $(this).addClass('hover-bound'),
    $msg = $hover.siblings('.dupe-hammer-message');

    $hover.hover(
    function() {
    $hover.showInfoMessage('', {
    messageElement: $msg.clone().show(),
    transient: false,
    position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
    dismissable: false,
    relativeToBody: true
    });
    },
    function() {
    StackExchange.helpers.removeMessages();
    }
    );
    });
    });
    Jan 11 '16 at 18:32


    This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





















      71












      71








      71


      22







      This question already has an answer here:




      • How to use a variable for a key in a JavaScript object literal?

        11 answers




      Is it at all possible to use variable names in object literal properties for object creation?



      Example



      function createJSON (propertyName){
      return { propertyName : "Value"};
      }

      var myObject = createJSON("myProperty");

      console.log(myObject.popertyName); // prints "value"
      console.log(myObject.myProperty); // Does not exist









      share|improve this question

















      This question already has an answer here:




      • How to use a variable for a key in a JavaScript object literal?

        11 answers




      Is it at all possible to use variable names in object literal properties for object creation?



      Example



      function createJSON (propertyName){
      return { propertyName : "Value"};
      }

      var myObject = createJSON("myProperty");

      console.log(myObject.popertyName); // prints "value"
      console.log(myObject.myProperty); // Does not exist




      This question already has an answer here:




      • How to use a variable for a key in a JavaScript object literal?

        11 answers








      javascript properties object-literal






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Aug 16 '14 at 19:47









      Bergi

      377k62573903




      377k62573903










      asked Jun 30 '10 at 22:49









      balafibalafi

      1,2001818




      1,2001818




      marked as duplicate by Bergi javascript
      Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

      StackExchange.ready(function() {
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function() {
      $hover.showInfoMessage('', {
      messageElement: $msg.clone().show(),
      transient: false,
      position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
      dismissable: false,
      relativeToBody: true
      });
      },
      function() {
      StackExchange.helpers.removeMessages();
      }
      );
      });
      });
      Jan 11 '16 at 18:32


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









      marked as duplicate by Bergi javascript
      Users with the  javascript badge can single-handedly close javascript questions as duplicates and reopen them as needed.

      StackExchange.ready(function() {
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function() {
      $hover.showInfoMessage('', {
      messageElement: $msg.clone().show(),
      transient: false,
      position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
      dismissable: false,
      relativeToBody: true
      });
      },
      function() {
      StackExchange.helpers.removeMessages();
      }
      );
      });
      });
      Jan 11 '16 at 18:32


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


























          4 Answers
          4






          active

          oldest

          votes


















          143














          If, in ES6, you want to use a variable for a property name, you can use the new ComputedPropertyName syntax. Place the variable name between square brackets:



          var foo = "bar";
          var ob = { [foo]: "something" }; // ob.bar === "something"


          In ES5, you have to create the object first, and then add the property using square bracket notation.



          var foo = "bar";
          var ob = {};
          ob[foo] = "something"; // === ob.bar = "something"


          If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the JSON.stringify method.






          share|improve this answer

































            38














            ES6 introduces computed property names, which allow you to do



            function CreateJSON (propertyName){
            var myObject = { [propertyName] : "Value"};
            }


            Note browser support is currently negligible.






            share|improve this answer
























            • interesting, any updates on browser support?

              – Ayyash
              Apr 15 '15 at 7:46











            • When I wrote the answer, only Firefox Nigthly. Now Firefox 34+ and Safari 7.1.3+, according to MDN.

              – Oriol
              Apr 15 '15 at 15:20











            • This is the best answer for me. I'm using nodejs.

              – James
              Feb 17 '16 at 12:45



















            7














            You can sort of do this:



              var myObject = {};
            CreateProp("myProperty","MyValue");

            function CreateProp(propertyName, propertyValue)
            {
            myObject[propertyName] = propertyValue;
            alert(myObject[propertyName]); // prints "MyValue"
            };


            I much perfer this syntax myself though:



            function jsonObject()
            {
            };
            var myNoteObject = new jsonObject();

            function SaveJsonObject()
            {
            myNoteObject.Control = new jsonObject();
            myNoteObject.Control.Field1= "Fred";
            myNoteObject.Control.Field2= "Wilma";
            myNoteObject.Control.Field3= "Flintstone";
            myNoteObject.Control.Id= "1234";
            myNoteObject.Other= new jsonObject();
            myNoteObject.Other.One="myone";
            };


            Then you can use the following:



            SaveJsonObject();
            var myNoteJSON = JSON.stringify(myNoteObject);


            NOTE: This makes use of the json2.js from here:http://www.json.org/js.html






            share|improve this answer































              5














              One thing that may be suitable (now that JSON functionality is common to newer browsers, and json2.js is a perfectly valid fallback), is to construct a JSON string and then parse it.





              function func(prop, val) {
              var jsonStr = '{"'+prop+'":'+val+'}';
              return JSON.parse(jsonStr);
              }

              var testa = func("init", 1);
              console.log(testa.init);//1


              Just keep in mind, JSON property names need to be enclosed in double quotes.






              share|improve this answer






























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                143














                If, in ES6, you want to use a variable for a property name, you can use the new ComputedPropertyName syntax. Place the variable name between square brackets:



                var foo = "bar";
                var ob = { [foo]: "something" }; // ob.bar === "something"


                In ES5, you have to create the object first, and then add the property using square bracket notation.



                var foo = "bar";
                var ob = {};
                ob[foo] = "something"; // === ob.bar = "something"


                If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the JSON.stringify method.






                share|improve this answer






























                  143














                  If, in ES6, you want to use a variable for a property name, you can use the new ComputedPropertyName syntax. Place the variable name between square brackets:



                  var foo = "bar";
                  var ob = { [foo]: "something" }; // ob.bar === "something"


                  In ES5, you have to create the object first, and then add the property using square bracket notation.



                  var foo = "bar";
                  var ob = {};
                  ob[foo] = "something"; // === ob.bar = "something"


                  If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the JSON.stringify method.






                  share|improve this answer




























                    143












                    143








                    143







                    If, in ES6, you want to use a variable for a property name, you can use the new ComputedPropertyName syntax. Place the variable name between square brackets:



                    var foo = "bar";
                    var ob = { [foo]: "something" }; // ob.bar === "something"


                    In ES5, you have to create the object first, and then add the property using square bracket notation.



                    var foo = "bar";
                    var ob = {};
                    ob[foo] = "something"; // === ob.bar = "something"


                    If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the JSON.stringify method.






                    share|improve this answer















                    If, in ES6, you want to use a variable for a property name, you can use the new ComputedPropertyName syntax. Place the variable name between square brackets:



                    var foo = "bar";
                    var ob = { [foo]: "something" }; // ob.bar === "something"


                    In ES5, you have to create the object first, and then add the property using square bracket notation.



                    var foo = "bar";
                    var ob = {};
                    ob[foo] = "something"; // === ob.bar = "something"


                    If you wanted to programatically create JSON, you would have to serialize the object to a string conforming to the JSON format. e.g. with the JSON.stringify method.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Dec 18 '17 at 9:13

























                    answered Jun 30 '10 at 22:51









                    QuentinQuentin

                    653k728871051




                    653k728871051

























                        38














                        ES6 introduces computed property names, which allow you to do



                        function CreateJSON (propertyName){
                        var myObject = { [propertyName] : "Value"};
                        }


                        Note browser support is currently negligible.






                        share|improve this answer
























                        • interesting, any updates on browser support?

                          – Ayyash
                          Apr 15 '15 at 7:46











                        • When I wrote the answer, only Firefox Nigthly. Now Firefox 34+ and Safari 7.1.3+, according to MDN.

                          – Oriol
                          Apr 15 '15 at 15:20











                        • This is the best answer for me. I'm using nodejs.

                          – James
                          Feb 17 '16 at 12:45
















                        38














                        ES6 introduces computed property names, which allow you to do



                        function CreateJSON (propertyName){
                        var myObject = { [propertyName] : "Value"};
                        }


                        Note browser support is currently negligible.






                        share|improve this answer
























                        • interesting, any updates on browser support?

                          – Ayyash
                          Apr 15 '15 at 7:46











                        • When I wrote the answer, only Firefox Nigthly. Now Firefox 34+ and Safari 7.1.3+, according to MDN.

                          – Oriol
                          Apr 15 '15 at 15:20











                        • This is the best answer for me. I'm using nodejs.

                          – James
                          Feb 17 '16 at 12:45














                        38












                        38








                        38







                        ES6 introduces computed property names, which allow you to do



                        function CreateJSON (propertyName){
                        var myObject = { [propertyName] : "Value"};
                        }


                        Note browser support is currently negligible.






                        share|improve this answer













                        ES6 introduces computed property names, which allow you to do



                        function CreateJSON (propertyName){
                        var myObject = { [propertyName] : "Value"};
                        }


                        Note browser support is currently negligible.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Aug 15 '14 at 19:48









                        OriolOriol

                        161k38268374




                        161k38268374













                        • interesting, any updates on browser support?

                          – Ayyash
                          Apr 15 '15 at 7:46











                        • When I wrote the answer, only Firefox Nigthly. Now Firefox 34+ and Safari 7.1.3+, according to MDN.

                          – Oriol
                          Apr 15 '15 at 15:20











                        • This is the best answer for me. I'm using nodejs.

                          – James
                          Feb 17 '16 at 12:45



















                        • interesting, any updates on browser support?

                          – Ayyash
                          Apr 15 '15 at 7:46











                        • When I wrote the answer, only Firefox Nigthly. Now Firefox 34+ and Safari 7.1.3+, according to MDN.

                          – Oriol
                          Apr 15 '15 at 15:20











                        • This is the best answer for me. I'm using nodejs.

                          – James
                          Feb 17 '16 at 12:45

















                        interesting, any updates on browser support?

                        – Ayyash
                        Apr 15 '15 at 7:46





                        interesting, any updates on browser support?

                        – Ayyash
                        Apr 15 '15 at 7:46













                        When I wrote the answer, only Firefox Nigthly. Now Firefox 34+ and Safari 7.1.3+, according to MDN.

                        – Oriol
                        Apr 15 '15 at 15:20





                        When I wrote the answer, only Firefox Nigthly. Now Firefox 34+ and Safari 7.1.3+, according to MDN.

                        – Oriol
                        Apr 15 '15 at 15:20













                        This is the best answer for me. I'm using nodejs.

                        – James
                        Feb 17 '16 at 12:45





                        This is the best answer for me. I'm using nodejs.

                        – James
                        Feb 17 '16 at 12:45











                        7














                        You can sort of do this:



                          var myObject = {};
                        CreateProp("myProperty","MyValue");

                        function CreateProp(propertyName, propertyValue)
                        {
                        myObject[propertyName] = propertyValue;
                        alert(myObject[propertyName]); // prints "MyValue"
                        };


                        I much perfer this syntax myself though:



                        function jsonObject()
                        {
                        };
                        var myNoteObject = new jsonObject();

                        function SaveJsonObject()
                        {
                        myNoteObject.Control = new jsonObject();
                        myNoteObject.Control.Field1= "Fred";
                        myNoteObject.Control.Field2= "Wilma";
                        myNoteObject.Control.Field3= "Flintstone";
                        myNoteObject.Control.Id= "1234";
                        myNoteObject.Other= new jsonObject();
                        myNoteObject.Other.One="myone";
                        };


                        Then you can use the following:



                        SaveJsonObject();
                        var myNoteJSON = JSON.stringify(myNoteObject);


                        NOTE: This makes use of the json2.js from here:http://www.json.org/js.html






                        share|improve this answer




























                          7














                          You can sort of do this:



                            var myObject = {};
                          CreateProp("myProperty","MyValue");

                          function CreateProp(propertyName, propertyValue)
                          {
                          myObject[propertyName] = propertyValue;
                          alert(myObject[propertyName]); // prints "MyValue"
                          };


                          I much perfer this syntax myself though:



                          function jsonObject()
                          {
                          };
                          var myNoteObject = new jsonObject();

                          function SaveJsonObject()
                          {
                          myNoteObject.Control = new jsonObject();
                          myNoteObject.Control.Field1= "Fred";
                          myNoteObject.Control.Field2= "Wilma";
                          myNoteObject.Control.Field3= "Flintstone";
                          myNoteObject.Control.Id= "1234";
                          myNoteObject.Other= new jsonObject();
                          myNoteObject.Other.One="myone";
                          };


                          Then you can use the following:



                          SaveJsonObject();
                          var myNoteJSON = JSON.stringify(myNoteObject);


                          NOTE: This makes use of the json2.js from here:http://www.json.org/js.html






                          share|improve this answer


























                            7












                            7








                            7







                            You can sort of do this:



                              var myObject = {};
                            CreateProp("myProperty","MyValue");

                            function CreateProp(propertyName, propertyValue)
                            {
                            myObject[propertyName] = propertyValue;
                            alert(myObject[propertyName]); // prints "MyValue"
                            };


                            I much perfer this syntax myself though:



                            function jsonObject()
                            {
                            };
                            var myNoteObject = new jsonObject();

                            function SaveJsonObject()
                            {
                            myNoteObject.Control = new jsonObject();
                            myNoteObject.Control.Field1= "Fred";
                            myNoteObject.Control.Field2= "Wilma";
                            myNoteObject.Control.Field3= "Flintstone";
                            myNoteObject.Control.Id= "1234";
                            myNoteObject.Other= new jsonObject();
                            myNoteObject.Other.One="myone";
                            };


                            Then you can use the following:



                            SaveJsonObject();
                            var myNoteJSON = JSON.stringify(myNoteObject);


                            NOTE: This makes use of the json2.js from here:http://www.json.org/js.html






                            share|improve this answer













                            You can sort of do this:



                              var myObject = {};
                            CreateProp("myProperty","MyValue");

                            function CreateProp(propertyName, propertyValue)
                            {
                            myObject[propertyName] = propertyValue;
                            alert(myObject[propertyName]); // prints "MyValue"
                            };


                            I much perfer this syntax myself though:



                            function jsonObject()
                            {
                            };
                            var myNoteObject = new jsonObject();

                            function SaveJsonObject()
                            {
                            myNoteObject.Control = new jsonObject();
                            myNoteObject.Control.Field1= "Fred";
                            myNoteObject.Control.Field2= "Wilma";
                            myNoteObject.Control.Field3= "Flintstone";
                            myNoteObject.Control.Id= "1234";
                            myNoteObject.Other= new jsonObject();
                            myNoteObject.Other.One="myone";
                            };


                            Then you can use the following:



                            SaveJsonObject();
                            var myNoteJSON = JSON.stringify(myNoteObject);


                            NOTE: This makes use of the json2.js from here:http://www.json.org/js.html







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jul 1 '10 at 20:19









                            Mark SchultheissMark Schultheiss

                            24.2k85283




                            24.2k85283























                                5














                                One thing that may be suitable (now that JSON functionality is common to newer browsers, and json2.js is a perfectly valid fallback), is to construct a JSON string and then parse it.





                                function func(prop, val) {
                                var jsonStr = '{"'+prop+'":'+val+'}';
                                return JSON.parse(jsonStr);
                                }

                                var testa = func("init", 1);
                                console.log(testa.init);//1


                                Just keep in mind, JSON property names need to be enclosed in double quotes.






                                share|improve this answer




























                                  5














                                  One thing that may be suitable (now that JSON functionality is common to newer browsers, and json2.js is a perfectly valid fallback), is to construct a JSON string and then parse it.





                                  function func(prop, val) {
                                  var jsonStr = '{"'+prop+'":'+val+'}';
                                  return JSON.parse(jsonStr);
                                  }

                                  var testa = func("init", 1);
                                  console.log(testa.init);//1


                                  Just keep in mind, JSON property names need to be enclosed in double quotes.






                                  share|improve this answer


























                                    5












                                    5








                                    5







                                    One thing that may be suitable (now that JSON functionality is common to newer browsers, and json2.js is a perfectly valid fallback), is to construct a JSON string and then parse it.





                                    function func(prop, val) {
                                    var jsonStr = '{"'+prop+'":'+val+'}';
                                    return JSON.parse(jsonStr);
                                    }

                                    var testa = func("init", 1);
                                    console.log(testa.init);//1


                                    Just keep in mind, JSON property names need to be enclosed in double quotes.






                                    share|improve this answer













                                    One thing that may be suitable (now that JSON functionality is common to newer browsers, and json2.js is a perfectly valid fallback), is to construct a JSON string and then parse it.





                                    function func(prop, val) {
                                    var jsonStr = '{"'+prop+'":'+val+'}';
                                    return JSON.parse(jsonStr);
                                    }

                                    var testa = func("init", 1);
                                    console.log(testa.init);//1


                                    Just keep in mind, JSON property names need to be enclosed in double quotes.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Jan 6 '12 at 2:19









                                    ChaseChase

                                    195210




                                    195210















                                        Popular posts from this blog

                                        MongoDB - Not Authorized To Execute Command

                                        in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

                                        How to fix TextFormField cause rebuild widget in Flutter