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
Source:stackexchange.com