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?
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).
Try using square bracket notation for the names
myObject['propa' + i] = foo;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With