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

Time:11-24

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

CodePudding user response:

You have to create a new object only if there isn't any already

if (!obj[id]) obj[id] = {}
if (!obj[id][qty]) obj[id][qty] = {}

I've added a loop to show how it works:

const ids = ['id1', 'id2']
const qtys = ['qty1', 'qty2']
const price = 1

const obj = {}

for (const id of ids) {
  for (const qty of qtys) {
    if (!obj[id]) obj[id] = {}
    if (!obj[id][qty]) obj[id][qty] = {}
    obj[id][qty] = Math.random() * 100 | 0
  }
}

console.log(obj)

CodePudding user response:

you always can spread

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