create object using variables for property name

javascript, object-literal, properties

Solution

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.

Problem

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 ```

Original source

Related problems