Search code examples
javascriptarraysobjectjavascript-objects

Unable to push to an array that is inside an object


I am trying to push some stuff into an array that lives inside my object. The thing is it runs, but when I view the object, the array remains empty even though I push into.

function add(){
    addItem = prompt("Where would you like to add this item to?")

    kitchen.forEach(function(item){
        if (addItem == item.belongsTo["fruits"]) {
            itemAdded = prompt("What would you like to add?");
            item.items[0].push(itemAdded);
        }else if(addItem == item.belongsTo["veggies"]){
            itemAdded = prompt("What would you like to add?");
            item.items[1].push(itemAdded);
        }
    });
}

function showKitchen(){
    kitchen.forEach(function(list){
        console.log(list);
    });
}


Solution

  • I just restructured the kitchen object so that you don't need to loop every time to add an item.

    // persist items with count
    const kitchen = {
      fruits: {},
      veggies: {}
    };
    
    function addItemToKitchen() {
      const group = prompt("Where would you like to add this item to?");
      if (group) {
        const itemToAdd = prompt(`What would you like to add in kitchen(${group}?`);
    
        if (itemToAdd) {
          // pick the group if found or create one
          kitchen[group] = kitchen[group] || {};
          // add item to group
          kitchen[group][itemToAdd] = (kitchen[group][itemToAdd] || 0) + 1;
    
          showKitchen();
        }
      }
    }
    
    function showKitchen() {
      Object.entries(kitchen).forEach(([group, items]) => {
        console.log(group, ':');
        Object.entries(items).forEach(([item, count]) => {
          console.log(`\t${item}(${count})`);
        });
      });
    }
    <button onclick="addItemToKitchen()">Add Item</button>
    <button onclick="showKitchen()">Show Kitchen List</button>