Trouble Accessing Value of Property

Hello,

I am trying to return the total cost of party supplies for an event, however the return I am getting is isNaN. Is the problem how I am accessing ‘supplies[j]’?

Regards :slight_smile:

const supplyList = { 
  plates: 2, 
  cups: 1,
  forks: 1,
  partyHats: 4 };

function orderSupplies(supplies, guests) {
  let totalCost = 0;
  for (let i = 0; i < guests; i++) {
    for (let j = 0; j < Object.keys(supplies).length; j++) {
      totalCost += supplies[j];
    }
  }
  return totalCost;
}

Hey! I have a question so I can understand a little better! Could you provide some more context around the supplyList and the number of supplies that you need per guest and if this changes at all? also could you let me know how much those individual supplies cost so we can consider this too? Many thanks, Tom

Hey there,

The cost of each item is the value to each items key (2 plates, 1 cup etc…).
I am simply trying to add the total cost of the SupplyList multiplied by the number of guests attending.

Cheers :slight_smile:

…Ah… I’m supposing that as object properties do not have indexes you cannot iterate over them?

You can iterate over an object’s keys with for (let supply in supplies) {. supply will be a key like plates. Then you can reference the value of a key (supply) by using supplies[supply].

FYI - You do not need the outer for loop because you can simply multiple the totalCost generated within the for loop by the number of guests.

1 Like

Hey @leedsleedsleedsleeds
Try this code! feel free to refactor :slight_smile: If you have any q’s let me know!

const supplyList = { 
    plates: 2, 
    cups: 1,
    forks: 1,
    partyHats: 4 };
  
  let totalSupplyList = (supplyList.plates + supplyList.cups + supplyList.forks + supplyList.partyHats)
  console.log(totalSupplyList)

  function totalCost(total, guests){
    let totalCost = total * guests
        console.log(`The total cost is £${totalCost}`)
  }

  console.log(totalCost(totalSupplyList, 5))

Many thanks,
Tom

@0tohero1 Your solution assumes the supplies object passed as the first argument of the function will always be the same. The better solution iterates through the object keys regardless how many properties the object has.