ZuriS
ZuriS

Reputation: 59

how to change user input from a number to a key and value of an object in JavaScript

First, I would like to apologise in advance if the Question is hard to understand..

I created 2 objects, one is a Drinks object and the other a Food object. The keys in both objects are the name of the drinks/food items and the values are the prices of those items. I then created two pop up boxes and outputted the keys and values of the objects in an ordered list on to the popups. The pop up boxes each have an input bar where the user can enter a number to select a menu item. What I am trying to do is create a function that will grab the number entered by the user when a button is clicked and based on that number, save corresponding the key and value of the objects (name of product and its price) to localStorage and then retrieve that information from the localStorage and display it in the Order/cart section.

What I'm struggling with is assigning the number entered to the corresponding key/value pair of the object. The following is the code I wrote trying to do the above mentioned:

// first we write empty arrays that will be used to store user input
let customerDrinkOrder = [];


//Drinks object:
let drinks = {
    "Earl gray ": 24.99,
    "Mocha ": 43.50,
    "Milkshake ": 36.60,
    "Coke ": 12.45,
    "Appletiser ":19.90
};

//bellow here we write a function that will get user input
function addDrinkToStorage(){
    let drinkInputVal = document.querySelector('#menuItemSelected').value;
    //here we want  to check if the input value isNaN, which it should be otherwise an error message will be displayed
    if(isNaN(drinkInputVal)){
        alert('ERROR! Please select menu item by number') //we arlet the error message 
    }
    //below we want to replace the user input values depending on what they are
    // with the keys and values of our drinks and food objects which we'll store in localStorage
    if(drinkInputVal === 1){
        drinkInputVal.toString().replace('1',Object.keys(drinks)[0]);
    }
    if(drinkInputVal===2){
        drinkInputVal.toString().replace('2',Object.keys(drinks)[1]);
    }
    if(drinkInputVal===3){
        drinkInputVal.toString().replace('3',Object.keys(drinks)[2]);
    }
    if(drinkInputVal===4){
        drinkInputVal.toString().replace('4', Object.keys(drinks)[3]);
    }
    if(drinkInputVal===5){
        drinkInputVal.toString().replace('4', Object.keys(drinks)[4]);
    }
    
    //here we push the new data to the back of the customerDrinkOrder  and customerFoodOrder arrays
    customerDrinkOrder.push(drinkInputVal);
    // customerFoodOrder.push(foodInputVal);
    //here we add a new property to the array in localStorage 
    //(customerDrinkOrder) and to the (customerFoodOrder)  using the dot notation and adding a new key[orders]
    localStorage.drinkOrders = JSON.stringify(customerDrinkOrder);
    // localStorage.foodOrders = JSON.stringify(customerFoodOrder);
}
//now we want to check if there's any data in the localStorage, we'll use if statements to do so
//if true, there is data in storage already
if(localStorage.drinkOrders){
    //here we get the data from localStorage and convert it back into a js array/object
    customerDrinkOrder = JSON.parse(localStorage.drinkOrders);
    
    console.log(customerDrinkOrder);
    
}

Upvotes: 0

Views: 457

Answers (1)

001
001

Reputation: 13533

I think this is what you want. See code for comments.

let drinks = {
  "Earl gray": 24.99,
  "Mocha": 43.50,
  "Milkshake": 36.60,
  "Coke": 12.45,
  "Appletiser": 19.90
};

document.getElementById("add-drink-btn").onclick = () => {
  // Get the number
  const drinkInputVal = document.getElementById("menuItemSelected").value;
  // Get the key
  const drinkInputName = Object.keys(drinks)[drinkInputVal - 1];
  // Create an object that will hold {<drink name> : <drink price>}
  // Example: {"Coke": 12.45}
  const toSave = {};
  toSave[drinkInputName] = drinks[drinkInputName];
  // Save to storage - won't work if sandboxed (like on Stack Overflow)
  try {
    localStorage.drinkOrders = toSave;
  } catch (e) {}
  // Log for debugging purposes
  console.log("Stored: " + JSON.stringify(toSave));
};

// Initialize list
const drinksList = document.getElementById("drinks-list");
let i = 1;
for (const d of Object.keys(drinks)) {
  let li = document.createElement("li");
  li.innerHTML = `${i++}. ${d} - ${drinks[d].toFixed(2)}`;
  drinksList.appendChild(li);
}
document.getElementById("menuItemSelected").max = i - 1;
<div>
  <ul id="drinks-list"></ul>
</div>
<label for="menuItemSelected">Select drink:</label><input type="number" id="menuItemSelected" min="1" value="1" />
<button id="add-drink-btn">Add drink to storage</button>

Upvotes: 1

Related Questions