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

java - HTTP Status 500 - An exception occurred processing JSP page /second.jsp at line 15 -

php - Using str_replace to translate a MySQL Table in html -

asp.net mvc - Cannot display error message on Editor or EditorFor -