Michael Shand
Michael Shand

Reputation: 1

Java Script OOP setting Object Key name and accessing Key name and values in methods

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

Upvotes: 0

Views: 62

Answers (1)

Abhale Amol
Abhale Amol

Reputation: 119

// 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

Upvotes: -1

Related Questions