Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create object using variables for property name [duplicate]

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 
like image 208
balafi Avatar asked Jun 30 '10 22:06

balafi


People also ask

Can we have two properties with the same name inside an object?

You cannot. Property keys are unique.


2 Answers

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.

like image 71
Quentin Avatar answered Oct 16 '22 02:10

Quentin


ES6 introduces computed property names, which allow you to do

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

Note browser support is currently negligible.

like image 40
Oriol Avatar answered Oct 16 '22 02:10

Oriol