Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create Instance fields for a JavaScript Object

Tags:

javascript

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 commented-out line shows what I am trying to do.

like image 695
John R Avatar asked Jan 19 '23 19:01

John R


1 Answers

You 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);
like image 153
Kirk Woll Avatar answered Mar 22 '23 23:03

Kirk Woll