Trying to add multiple properties to Javascript object using a loop

47,604

Solution 1

Try using square bracket notation for the names

   myObject['propa' + i] = foo;

Solution 2

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.

Solution 3

Use the array-access method to set the properties.

myObject = {  };

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

Solution 4

you might use

object['popA'+i]=... 

to create a standard property or either use a getter/setter property, in this case you need to use

Object.defineProperty(object, *propertyname*, *propertyDescriptor*).  

The latter gives you more options on the created property.

All details here :
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty

Share:
47,604
Jonathon Nordquist
Author by

Jonathon Nordquist

Updated on July 09, 2022

Comments

  • Jonathon Nordquist
    Jonathon Nordquist almost 2 years

    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?

  • Jonathon Nordquist
    Jonathon Nordquist about 11 years
    This in fact did it, much obliged.
  • Jonathon Nordquist
    Jonathon Nordquist about 11 years
    This has proved useful as well, some of the objects in my current project work better as groups of arrays.