Loop through an object with a key input to give the corresponding value in JavaScript

Viewed 30

How can I loop through the array to give the correct value of the drinks order. The loop does not stop with the correct value.

let x = {
    coke: "9.50",
    sprite: "10.50",
    fanta: "11.50",
    juice: "12.50",
    grapetiser: "13.00"
}

let drinksOrderInput = prompt("Select your Softdrink");
for (let i = 0; i < arr.length; i++) {
    let arrKey = Object.keys(x);
    let arrValue = Object.values(x);
    if (arrKey[i] == drinksOrderInput) {
        alert("Thank you for the order");
        let drinkOrder = arrValue[i];
        sessionStorage.setItem("drinks", JSON.stringify(drinkOrder));
        break;
    } else {
        alert("Please check the menu and enter a valid softdrink");
    }
}
1 Answers

The first mistake is, that you try to get the length of "arr" but this isn't defined. But to get the length of your object you can use Object.keys(x).length. See code below

let x = { coke: "9.50", sprite: "10.50", fanta: "11.50", juice: "12.50", grapetiser: "13.00" }

let drinksOrderInput = prompt("Select your Softdrink");

for (var i = 0; i < Object.keys(x).length; i++) {
    let arrKey = Object.keys(x);
    let arrValue = Object.values(x);
    if (arrKey[i] == drinksOrderInput) {
        alert("Thank you for the order");
        let drinkOrder = arrValue[i];
        sessionStorage.setItem("drinks", JSON.stringify(drinkOrder));
        break;
    } else {
        alert("Please check the menu and enter a valid softdrink");
    }
}

Related