[Vuejs]-Cannot read property of undefined when trying to access a method from another method

2πŸ‘

βœ…

In Javascript this acts differently than other languages like Java.
Please read this mdn page.

When you use this inside forEach, it refers to forEach context.

To answer your question, you can store this in a variable:

var self = this;
restrictedDishes.forEach(function(item){
    specifications.push({
        type: "Dish",
        item: item.name,
        meals: self.getStringMeals(item.pivot.breakfast,item.pivot.snack1,item.pivot.lunch,item.pivot.snack2,item.pivot.dinner)
    })});

Or use fat arrow syntax:

restrictedIngredients.forEach((obj) => {
   specifications.push({
       type: "Ingredient",
       item: item.name,
       meals: this.getStringMeals(item.pivot.breakfast,item.pivot.snack1,item.pivot.lunch,item.pivot.snack2,item.pivot.dinner)
       })});
πŸ‘€Pranav Kale

1πŸ‘

Use the arrow function for forEach as shown below.

restrictedIngredients.forEach((obj) => {
                    specifications.push({
                        type: "Ingredient",
                        item: item.name,
                        meals: this.getStringMeals(item.pivot.breakfast,item.pivot.snack1,item.pivot.lunch,item.pivot.snack2,item.pivot.dinner)
                    })
                })
πŸ‘€Shashikant

Leave a comment