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..?
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..?
Share Improve this question asked Nov 21, 2009 at 18:12 danpdanp 15.3k7 gold badges46 silver badges48 bronze badges1 Answer
Reset to default 10You 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";