cdmt
cdmt

Reputation: 923

Angular - generate array of objects and display the data

I have a demo here https://stackblitz.com/edit/angular-w7vavy

I'm trying to create a function that will generate an array of objects that contain random numbers an then output the array on the screen

I just getting an error - Error: Cannot set property '0' of undefined

createData = () => {
    for(let n=0; n<=this.dates.length;n++){
      for(let i= 0; i<=4; i++){
        this.testData[i] = {
          data_1: Math.random() * (this.max - this.min),
          data_2: Math.random() * (this.max - this.min),
          data_3: Math.random() * (this.max - this.min),
          data_4: Math.random() * (this.max - this.min),
          date: this.dates[i]
        }
      }
    }
}

Upvotes: 0

Views: 199

Answers (3)

fiveobjects
fiveobjects

Reputation: 4289

I think initialization has to be taken care properly. I removed typescript syntax and made it plain JS. Here you go:

testData = []
dates = ['2014', '2015', '2016', '2017']

min = 10;
max = 100;
createData = () => {
    for (let n = 0; n <= dates.length; n++) {
        for (let i = 0; i < 4; i++) {
            testData[i] = {
                data_1: Math.random() * (max - min),
                data_2: Math.random() * (max - min),
                data_3: Math.random() * (max - min),
                data_4: Math.random() * (max - min),
                date: dates[i]
            }
        }
    }
}
createData();
console.log(testData);

Upvotes: 1

Guntram
Guntram

Reputation: 980

Initialize this.testData = [] before the loop, use this.testData.push({...the object...}) inside the loop. Maybe this.dates has to be initialized also.

Upvotes: 2

Tesmen
Tesmen

Reputation: 589

You need to explicitly define testData in your code before loop.

this.testData = [];

Upvotes: 2

Related Questions