Javascript Objects (dynamic attribute names) -


if have object, this

var o = {   test : 1 } 

and have second object, 1 of it's keys should value of o.test. this:

var o2 = {    o.test : "bla" } 

i know not possible, there better (cleaner) way do now?

currently dow this:

var o2 = {}; o2[o.test] = "bla" 

i guess there better way this?

i guess there better way this?

assuming i've understood question correctly no, not really. way you've shown way it. there no way use dynamic key inside literal itself, have declare first , assign property separately:

var o2 = {}; o2[o.test] = "bla";  o2; // { 1: "bla" } 

update

the full details given in spec. here's grammar object literal property identifiers:

propertyname :
    identifiername
    stringliteral
    numericliteral

the stringliteral production self-explanatory. here's identifiername production does:

the production propertyname : identifiername evaluated follows:

  1. return string value containing same sequence of characters identifiername.

and numericliteral production:

the production propertyname : numericliteral evaluated follows:

  1. let nbr result of forming value of numericliteral.
  2. return tostring(nbr).

you can see not possible use other string inside object initialiser.


Comments

Popular posts from this blog

Using 'OR' and 'AND' in SQL Server -

python - Finding intersection between ellipse and a line -

c++ - NetBeans Remote Development with additional configuration -