111

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
0

4 Answers 4

251

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.

Sign up to request clarification or add additional context in comments.

Comments

51

ES6 introduces computed property names, which allow you to do

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

Note browser support is currently negligible.

4 Comments

interesting, any updates on browser support?
When I wrote the answer, only Firefox Nigthly. Now Firefox 34+ and Safari 7.1.3+, according to MDN.
This is the best answer for me. I'm using nodejs.
As of 2020, all browsers now support computed property names except for IE.
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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.