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
Post a Comment