I have a dynamically-created list of strings called 'variables'. I need to use these strings as the instance variables for an array of JavaScript objects.
var objectsArr = [];
function obj(){};
for (var i=0; i<someNumberOfObjects; i++ ) {
...
objectsArr[i] = new Object();
for (var j=0; j<variables.length; j++) {
objectArr[i].b = 'something'; //<--this works, but...
//objectArr[i].variables[j] = 'something'; //<---this is what I want to do.
}
}
The mented-out line shows what I am trying to do.
I have a dynamically-created list of strings called 'variables'. I need to use these strings as the instance variables for an array of JavaScript objects.
var objectsArr = [];
function obj(){};
for (var i=0; i<someNumberOfObjects; i++ ) {
...
objectsArr[i] = new Object();
for (var j=0; j<variables.length; j++) {
objectArr[i].b = 'something'; //<--this works, but...
//objectArr[i].variables[j] = 'something'; //<---this is what I want to do.
}
}
The mented-out line shows what I am trying to do.
Share Improve this question edited Sep 6, 2011 at 3:24 RobG 148k32 gold badges179 silver badges214 bronze badges asked Sep 6, 2011 at 3:14 John RJohn R 3,03613 gold badges51 silver badges62 bronze badges2 Answers
Reset to default 9You can use the bracket syntax to manipulate the property by name:
objectArr[i][variables[j]] = 'something';
In other words, get the object from objectArr
at index i
then find the field with name variables[j]
and set the value of that field to 'something'
.
In general terms, given object o
:
var o = {};
You can set the property by name:
o['propertyName'] = 'value';
And access it in the usual way:
alert(o.propertyName);
Use the bracket notation. This will get it done:
var objectsArr = [], ii, jj;
function Obj() {}
for(ii = 0; ii < someNumberOfObjects; ii += 1) {
objectsArr[ii] = new Obj();
for (jj = 0; jj < variables.length; jj += 1) {
objectArr[ii][variables[jj]] = 'something';
}
}
A couple of additional notes:
- Javascript doesn't have block scope, so you must have two separate loop variables.
- By convention, constructor functions like
Obj
should begin with a capital letter to signify that they ought to be used with thenew
keyword. In this case though, unless you need the objects to have a non-Object prototype, you could just use a plain object literal (objectsArr[ii] = {};
).