samedi 4 août 2018

Incorporating if statement with JavaScript objects that has nested arrays with multiple values

My below code works perfectly, however I have hit a wall when I try and create a nested array to add more values to my 'item' property. I'm not sure how to incorporate this nested array with multiple items into my if statement. I'm able to capture a single index (the code I have now) ex. milk, will tell me that it's in aisle 1, but when I add multiple items in a created nested array ex. ["milk", "cheese", "eggs"], my code does nothing, it does not search through all items in the 'item' property. I would like to add multiple items to the each aisle. ex.

aisle: "Aisle 1",
item: ["milk", "cheese", "eggs"], 

aisle: "Aisle 2", 
item: ["lettuce", "tomatoes", "onions"],

If someone would be so kind to point me in the right direction or possible documentation on this matter. I have researched everywhere and I'm having a hard time finding material on nested arrays that involve both a for loop and an if statement.

End Goal: The user types in an item from the word bank form, and the application will let them know what aisle it is hiding in. I want to use Vanilla Javascript, I am not interested in jQuery. Yes, I'm a beginner.

<form>
  <input type="text" name="productName" value="" id ="input">
</form>
<button type="button" value = "" onclick="start()" id ="input">Click Me!</button>

<br>

<div class="jumbotron">
  <h2 class="display-4">Work Bank</h2>
  <p class="lead">Milk, Lettuce, Shampoo</p>
</div>


 function start(){
      var products = [
      {
        aisle: "Aisle 1",
        item: "milk",  
        onSale: false,
      },
      {
        aisle: "Aisle 2", 
        item: "lettuce", 
        onSale: true,
      },
      {
        aisle: "Aisle 3", 
        item: "shampoo",
        onSale: false,
      }
      ]

      for(i = 0; i < products.length; i++){
        if (products[i].item === document.getElementById('input').value){
          console.log("Your item " + '(' + products[i].item + ')'+ " is in " + products[i].aisle);
        }  
      } 
    }

Aucun commentaire:

Enregistrer un commentaire