create object using variables for property name [duplicate]

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


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

var myObject = createJSON("myProperty");

console.log(myObject.propertyName);  // Prints "value"
console.log(myObject.myProperty);  // This property does not exist



ES6 introduces computed property names, which allow you to do

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

Note browser support is currently negligible.


You can sort of do this:

  var myObject = {};

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

Then you can use the following:

var myNoteJSON = JSON.stringify(myNoteObject);

NOTE: This makes use of the json2.js from here:


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

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


If you want to use a variable for a property name, you can use Computed Property Names. Place the variable name between square brackets:

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

If you want Internet Explorer support you will need to use the ES5 approach (which you could get by writing modern syntax (as above) and then applying Babel):

Create the object first, and then add the property using square bracket notation.

var foo = "bar";
var ob  = {};
ob[foo] = "something"; // === = "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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.