1

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);
      }
    });
  }

2 Answers 2

8

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[] = []
Sign up to request clarification or add additional context in comments.

Comments

4

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

categories: Category[] = [];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.