Dynamically create instance fields for a JavaScript object

I have a dynamically created list of strings called "variables". I need to use these lines as 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 recorded line shows what I'm trying to do.

+4
source share
2 answers

Console syntax can be used to manage a property by name:

 objectArr[i][variables[j]] = 'something'; 

In other words, get the object from objectArr in index i , then find the field named variables[j] and set this value to 'something' .

In general terms, this object is o :

 var o = {}; 

You can set the property by name:

 o['propertyName'] = 'value'; 

And access it in the usual way:

 alert(o.propertyName); 
+9
source

Use parenthesis notation. This will be 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 few additional notes:

  • Javascript has no block scope, so you must have two separate loop variables.
  • By convention, constructor functions, such as Obj , must start with a capital letter to indicate that they should be used with the new keyword. However, in this case, if you do not need objects for the non-Object prototype, you can simply use a simple object literal ( objectsArr[ii] = {}; ).
0
source

All Articles