Search code examples
javascripttypescriptobjectkey-value

javascript: Building an object inside an object and adding key/value pairs to it


I start out with an empty object in the global scope and then I fetch an ID at a time to which I'd like to add prices together with a quantity. The script iterates through a list and for each row the ID is present, I wish to add quantity: price

I want my object to look something like this:

const obj = {
  id1: {
    qty1: price
    qty2: price
    qty3: price
    qty4: price
    qty5: price
    qty6: price
    qty7: price
  }
  id2: {
    qty1: price
    qty2: price
    qty3: price
    qty4: price
    qty5: price
    qty6: price
    qty7: price
  }
}

Currently I'm just getting one price as each run replaces the other.

const obj = {}
obj[id] = { [qty]: price }

// Result
obj: {
  id: {
    qty: price
  }
}

Solution

  • you always can spread

    const obj = {}
    obj[id] = {...obj[id], qty: price }