4

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.

2 Answers 2

9

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);
Sign up to request clarification or add additional context in comments.

1 Comment

That did it. Thanks you for the fast reply.
0

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 the new 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] = {};).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.