0

I have to create a bill calculator for a cafe that takes the value of a prompt box (which also displays the various options on the menu & adds the value of the Object property (price) to a bill total

//Drinks Object  
var drinks = {  
    guinness: 40,  
    kilkenny: 46,  
    stellaArtois: 28,  
    longIslandIcedTea: 35,  
    orangeJuice: 19,    
};

//Food Object  
var food = {  
    toastedSandwich: 25,  
    cheeseburger: 55,  
    pizza: 75,  
    spaghettiBolognese: 48,  
    rumpSteak: 150,  
};

Is it possible to use an if else statement within the function to Validate the users input in the prompt box against the food or drinks object property names only? and add that choices value to a total calculator?

Eg.

var total = 0;

function displayMenu1() {  
    var inputDrink = prompt("What drink would you like to order?, We have: " + Object.getOwnPropertyNames(drinks));  
        if (inputDrink.value == drinks.guinness || drinks.kilkenny || drinks.stellaArtois || drinks.longIslandIcedTea || drinks.orangeJuice) {  
            alert("Great Choice!");  
    }else {  
        alert("Please choose a valid option from the menu");   
    }  
}

I know the code is not complete, I am just curious as to how I can compare input against the object property names versus the property values.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Runexer
  • 19
  • 5
  • 2
    Possible duplicate of [Checking if a key exists in a JavaScript object?](https://stackoverflow.com/q/1098040/218196) – Felix Kling Feb 06 '19 at 21:02

1 Answers1

0

In the same way you listed out the options using Object.getOwnPropertyNames to generate an array of the valid options, you can check that array to see if the user's input is in there. From there, you can grab the value associated with that drink and add it on to your total. You can see after calling the function twice, the total gets updated.

var drinks = {
  guinness: 40,
  kilkenny: 46,
  stellaArtois: 28,
  longIslandIcedTea: 35,
  orangeJuice: 19,
};

//Food Object  
var food = {
  toastedSandwich: 25,
  cheeseburger: 55,
  pizza: 75,
  spaghettiBolognese: 48,
  rumpSteak: 150,
};

var total = 0;

function displayMenu1() {
  var inputDrink = prompt("What drink would you like to order?, We have: " + Object.getOwnPropertyNames(drinks));
  if (Object.getOwnPropertyNames(drinks).includes(inputDrink)) {
    total += drinks[inputDrink];
    alert("Great Choice!  New total is " + total);
  } else {
    alert("Please choose a valid option from the menu");
  }
}

displayMenu1();
displayMenu1();
larz
  • 5,724
  • 2
  • 11
  • 20