Variable as the property name in a JavaScript object literal? -


this question has answer here:

possible duplicate:
how add property javascript object using variable name?
use variable property name in javascript literal?

is possible add variable property name of object in javascript, this:

var myvar = "name"; var myobject = {     {myvar}: "value" }; 

you can use [] syntax use expression property name (compared .prop , prop: value syntaxes treated strings):

var myobject = {}; var myvar = "name"; myobject[myvar] = "value"; 

there no way use inside object literal, though. have create object first , assign each property separately.


edit

with es6, possible using computedpropertyname, manifests in form of following syntax:

var myvar = "name"; var myobject = {     [myvar]: "value" }; 

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -