Zach Starnes
Zach Starnes

Reputation: 3198

Typescript undefined is not an object when pushing to array

I am trying to push to an array but it keeps giving me this error:

Uncaught (in promise): TypeError: Cannot read property 'push' of undefined
TypeError: Cannot read property 'push' of undefined

here is the source where I am simply adding to an array. I take the obsevable from the firestore collection and loop through it. Why is it giving me this error when the array of category objects is right there. categories: Category[];

transactions: Observable<Transaction[]>;
categories: Category[];

private organizeData() {
    let category: Category;

    this.transactions.forEach(v => {
      for (let i = 0; i < v.length; i++) {
        category = {name: v[i].category, totalSpent: v[i].amount};
        this.categories.push(category);
      }
    });
  }

Upvotes: 1

Views: 5645

Answers (2)

mahval
mahval

Reputation: 2213

You are not initiating your array categories so it will return undefined. Try:

categories: Category[] = [];

Upvotes: 4

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249736

categories: Category[] is just the declaration of an array, you need to actually create a new array and assign it to the field:

categories: Category[] = []

Upvotes: 8

Related Questions