0

Essentially, I am trying to create a for loop which creates an object containing each candy's name and price. I can access the inventory for a certain day with no problems using this

console.log(store3[4]['inventory sold'])

{ 'Dark Chocolate Crunchies': { cost: 4.29, quantity: 2 },
  'Mint Wafers': { cost: 1.09, quantity: 1 },
  'Peppermint Poppers': { cost: 2.38, quantity: 0 },
  'Peanut Butter Buttered Peanuts': { cost: 1.79, quantity: 2 },
  'Berry Bites': { cost: 7.89, quantity: 5 },
  'Caramel Twists': { cost: 0.5, quantity: 7 },
  'Banana Bunches': { cost: 4.53, quantity: 2 } }

As well as this

console.log(store3[4]['inventory sold']['Mint Wafers'])

{ cost: 1.09, quantity: 1 }

However, for a for loop, I need to use numerical values, and for some reason I get undefined when I try to run the prior command in this format. Any suggestions?

console.log(store3[4]['inventory sold'][1])

undefined
0

1 Answer 1

2

You can use Object.keys to get an array of keys only, then you forEach on this array and you will be abled to access every attribute of your objects.

var datas = { 
  'Dark Chocolate Crunchies': { cost: 4.29, quantity: 2 },
  'Mint Wafers': { cost: 1.09, quantity: 1 },
  'Peppermint Poppers': { cost: 2.38, quantity: 0 },
  'Peanut Butter Buttered Peanuts': { cost: 1.79, quantity: 2 },
  'Berry Bites': { cost: 7.89, quantity: 5 },
  'Caramel Twists': { cost: 0.5, quantity: 7 },
  'Banana Bunches': { cost: 4.53, quantity: 2 }
}


Object.keys(datas).forEach(function (key) {
  console.log(key) ;
  console.log('cost',datas[key]['cost']) ;
  console.log('quantity',datas[key]['quantity']) ;
}) ;

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This is extremely helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.