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" };
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
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.
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.
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.
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.
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 this?
var myVar = "name"; var myObject = {}; myObject[myVar] = "value";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With