110

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.propertyName);  // Prints "value"
console.log(myObject.myProperty);  // This property does not exist
Kajal Sinha
  • 1,565
  • 11
  • 20
balafi
  • 2,143
  • 3
  • 17
  • 20

4 Answers4

245

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" }; // ob.bar === "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"; // === 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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
50

ES6 introduces computed property names, which allow you to do

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

Note browser support is currently negligible.

Oriol
  • 274,082
  • 63
  • 437
  • 513
  • interesting, any updates on browser support? – Ayyash Apr 15 '15 at 07:46
  • When I wrote the answer, only Firefox Nigthly. Now Firefox 34+ and Safari 7.1.3+, according to [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Browser_compatibility). – 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
  • As of 2020, all browsers now support computed property names except for IE. – BenHohner Nov 21 '20 at 20:16
10

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

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
6

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.

Chase
  • 370
  • 5
  • 12