Javascript Objects (dynamic attribute names)

javascript, object

Solution

I guess there is a better way for this?

Assuming I've understood your question correctly then no, not really. The way you've shown is the way to do it. There is no way to use a dynamic key inside the literal itself, so you have to declare it first and then assign the property separately:

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

o2; // { 1: "bla" }

Update

The full details are given in the spec. Here's the grammar for object literal property identifiers:

PropertyName : IdentifierName StringLiteral NumericLiteral

The StringLiteral production is self-explanatory. Here's what the IdentifierName production does:

The production PropertyName : IdentifierName is evaluated as follows:

- Return the String value containing the same sequence of characters as the IdentifierName.

And for the NumericLiteral production:

The production PropertyName : NumericLiteral is evaluated as follows:

- Let nbr be the result of forming the value of the NumericLiteral.

- Return ToString(nbr).

You can see from this that it is not possible to use anything other than a string inside an object initialiser.

Problem

if I have an object, something like this ``` var o = { test : 1 } ``` and I would like to have a second object, one of it's keys should be the value of o.test. Something like this: ``` var o2 = { o.test : "bla" } ``` I know this is not possible, but is there a better (cleaner) way to do it as I do this now? Currently what I dow is this: ``` var o2 = {}; o2[o.test] = "bla" ``` I guess there is a better way for this?

Original source