views:

84

answers:

1

I'm trying to initialise some data values dynamically inside a javascript object, but when I create a concatenated string to pass along, the actual key stored is the variable name, instead of the value inside it.

Example:

projects.init = function(){
 for (var i = this.numBoxes - 1; i >= 0; i--){
  var toInject = "item"+i;
  this.datas[i] = {toInject:"testdata"};
 };
}

Then after calling init, the values inside projects.datas look like.. toInject "testdata", instead of being "item1"..."item2".... what am I doing wrong..?

+4  A: 

You should build your object in two steps, and use the bracket notation property accessor:

projects.init = function(){
        for (var i = this.numBoxes - 1; i >= 0; i--){
                var toInject = "item"+i,
                    obj = {};

                obj[toInject] = "testdata";
                this.datas[i] = obj;
        };
}

The labels on object literals cannot be expressions.

As you can see, first you declare an empty object literal:

var obj = {};

And then you set the property:

obj[toInject] = "testdata";
CMS
Is there a reference explaining this in more detail? I'm sure this works, but would be nice to know why ;)
danp
obj[toInject] is like saying eval( "obj." + toInject); it sets the property with the name in the variable toInject. :D
CrazyJugglerDrummer
Thanks for the update, perfect.
danp
It's fairly simple. Property ID's in JSON are not allowed to be variables. If you want to use a variable to reference or create a property, you have to use array notation as CMS has shown.
Justin Johnson
@CrazyJugglerDrummer: There are some property names that cannot be accessed by the dot notation, for example a property name that contains a (`-`) dash, evaling that will just make a syntax error, because the compiler will find the dash and it will interpret it as the arithmetic substraction operator, in an invalid operation.
CMS
Unquoted words in object literal keys being taken as strings: another of JavaScript's bizarre mistakes.
bobince