Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to add multiple properties to Javascript object using a loop

I hope the day finds you well.

So I have an object with no properties. I'm trying to add multiple properties to this object using a loop. Each property added to the loop will appear in the object multiple times depending on how many times the loop runs, with each new property incremented by 1.

So I have something like this:

myObject = {  };

for(i = 0; i < 2; i++){
    myObject.propA + i = foo;
    myObject.propB + i = bar;
};

Which I want to yield something like this:

myObject.propA0 = foo;
myObject.propB0 = bar;
myObject.propA1 = foo;
myObject.propB2 = bar;

Giving a nice stack of objects generated on the fly depending on how many times the loop runs. But I don't seem to be getting this. So how exactly do I feed the variable from the loop to the property when it's created and assigned?

like image 590
Jonathon Nordquist Avatar asked Apr 09 '13 16:04

Jonathon Nordquist


People also ask

Which JavaScript loop loops through the properties of an object?

Description. The loop will iterate over all enumerable properties of the object itself and those the object inherits from its prototype chain (properties of nearer prototypes take precedence over those of prototypes further away from the object in its prototype chain).


2 Answers

Try using square bracket notation for the names

   myObject['propa' + i] = foo;
like image 167
TommyBs Avatar answered Sep 17 '22 08:09

TommyBs


As other users said, you have to use bracket notation to refer to properties by their name strings:

myObject['propA' + i] = 'foo';

But why don't you use an array of objects, instead of a single object with similar, numbered property names? Something like this:

var myArray = [];
for(i = 0; i < 2; i++){
    myArray.push({
        propA: 'foo',
        propB: 'bar'
    });
};

This should produce:

[
    { propA: 'foo', propB: 'bar'},
    { propA: 'foo', propB: 'bar'}
]

It looks way cleaner, in my opinion.

like image 34
bfavaretto Avatar answered Sep 17 '22 08:09

bfavaretto