0
function Inventory(item, price){
  const newObj = {};
        this.item = {
        price: price,
        quantity: 1,
      };

/*I tried this too 
  [item] = {
        price: price,
        quantity: 1,
      };
      */
}


  Inventory.prototype.addItem = function(item, price){
    if(item !== this.item){
      const newInv = new Inventory(item,price);
      return newInv;
  
    }else{
      this.item.quantity++;
      this.item.price = price;
    }
  };

I am working through CSX OOP and I have been stuck for a few days now. I am trying to set the objects key name in the constructor based off the input argument item and then have an object inside that key value. But with this.item it just displays item. So i tried to make a new object and set it to newObj[item] that worked. But when I did this I can not longer access the other keys inside the value of newObj[item]. When its this.item i can access the object inside the value but then the key of item never changes with my arugments.

In short, I need to be able to change the key name based off the arguments and then later access that key name. and I cannot figure out how to do this. Please help

Chris G
  • 1,598
  • 1
  • 6
  • 18
  • It's really unclear what your asking here, but looking at the code it seems a little bit confusing, something called `Inventory` I would expect multiple items, eg. an array of items, and when you call the add I would expect that to look at the array etc. – Keith Feb 22 '23 at 14:51
  • I am making creating an object in the constructor and the key name needs to be the item argument in Inventory. The key value of item contains two key-value pairs, price: set to the price argument and quantity starting at 1. Then in the add method I am adding a new Inventory if the passed in item(in addItem) has not already been created. – Michael Shand Feb 22 '23 at 15:50

1 Answers1

-1

// try bellow logic

newObject = []; // creating empty array to store elements

item = {}; // creating empty item object

item.price = <>; item.quantity = <>;

newObject.push(item); // storing/pushing item in newObject array

Abhale Amol
  • 109
  • 4