I am trying to pass in an ‘order’ function to ‘orderDelivery’ function through objects to synchronize with the order instead of hard coding it at the bottom
const restaurant = {
name: 'Classico Italiano',
location: 'Via Angelo Tavanti 23, Firenze, Italy',
categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
mainMenu: ['Pizza', 'Pasta', 'Risotto'],
openingHours: {
thu: {
open: 12,
close: 22,
},
fri: {
open: 11,
close: 23,
},
sat: {
open: 0,
close: 24,
},
},
order: function (starterIndex, mainIndex) {
return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
},
orderDelivery: function({starterIndex, mainIndex, time, address}) {
// ({starterIndex, mainIndex}) = this.order(2,1) attempt 1 - destructuring
// this.order(2,1) attempt 2 - logging shows correct order but undefined
console.log(`Order received! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be delivered to ${address} at ${time}`);
}
};
// const myOrder = restaurant.order(2, 1); attempt 3
restaurant.orderDelivery({
time: '22:30',
address: 'Via del Sole, 21',
// mainIndex: myOrder[0], attempt from 3
// starterIndex: 2, hard code
});
I have tried destructuring but something tells me I would have to use the order function in the orderDelivery function that is outside the object but I am not really sure how. I tried assigning the order function outside and pass it through the orderDelivery but same undefined result.
2
Answers
You probably meant to build a
class
rather than regular Object – but here is how to do it without Classes:You are getting
undefined
because when you callrestaurant.orderDelivery()
you must pass params spelled in exact way you defined them inorderDelivery
function. This is how object destructuring works.You are basically defined a function which accepts an
object
with some desired properties as argument, so you have to pass this object with its properties in order to work. If a property is not supplied, the value of it is going to beundefined
.Another point is your
order
, which returns an array composed by an element of starterMenu and one of mainMenu, so doing myOrder[0] in your case returns a string, not an index (which I guess is what you want)If you want the index of that items you should use
Array.indexOf()
on the right array containing the item you are looking for:This kinda works but is a little bit tricky. You could move this searching logic inside
orderDelivery
function and instead ofstarterIndex
andmainIndex
you directly passorder()
output:So you can call restaurant.orderDelivery() in this way: