0

Currently receiving an undefined error when attempting to assign property values to a collection of objects.

Code:

MyArray = []; 
for(let j=0; j<5; j++) {
    MyArray[j].randoAttribute = 2;
    MyArray[j].anotherRandoAttrbute = 3;
}

Error message:

TypeError: Cannot set properties of undefined (setting 'randoAttribute')

Goal: How do I avoid this error and still be able to dynamically assign property values in an iterator?

generic3892372
  • 133
  • 2
  • 11
  • `MyArray[j]` doesn’t exist, so you can’t set properties on it. You need to [create objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer). Simply do `MyArray.push({ randoAttribute: 2, anotherRandoAttrbute: 3 });` in the loop. – Sebastian Simon Mar 09 '22 at 23:11

0 Answers0