Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable as the property name in a JavaScript object literal? [duplicate]

Tags:

javascript

Possible Duplicate:
How do I add a property to a Javascript Object using a variable as the name?
Use variable for property name in JavaScript literal?

Is it possible to add a variable as the property name of an object in JavaScript, like this:

var myVar = "name"; var myObject = {     {myVar}: "value" }; 
like image 716
jsgroove Avatar asked Jun 15 '12 00:06

jsgroove


People also ask

Can object in JavaScript have duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

Are properties variables in JavaScript?

This data within JavaScript is contained as fields (properties or variables) and code (procedures or methods). Properties and variables are similar in nature, but properties are specifically tied to objects while variables are not.

What are property names in JavaScript?

The function name property of the javascript object is used to return the name of the function. This name property of the function is only readable and cannot be altered. The name of the function which was given when the function was created is returned by Function.name.

What is JavaScript object literal?

Object Literal. In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions.


2 Answers

You can use the [] syntax to use an expression as the property name (compared to the .prop and prop: value syntaxes where they are always treated as strings):

var myObject = {}; var myVar = "name"; myObject[myVar] = "value"; 

There is no way to use that inside an object literal, though. You have to create the object first and then assign each property separately.


Edit

With ES6, this is now possible using a ComputedPropertyName, which manifests in the form of the following syntax:

var myVar = "name"; var myObject = {     [myVar]: "value" }; 
like image 83
ThiefMaster Avatar answered Oct 12 '22 15:10

ThiefMaster


Like this?

var myVar = "name"; var myObject = {};  myObject[myVar] = "value"; 
like image 28
Blender Avatar answered Oct 12 '22 15:10

Blender