Home > Enterprise >  looping over objects javascript
looping over objects javascript

Time:09-23

So recently I learned about using for in loops to loop over objects. We were given this problem to solve regarding a basic cart object that contains name of object and then quantity and price.

const cart = {
  "Gold Round Sunglasses": { quantity: 1, priceInCents: 1000 },
  "Pink Bucket Hat": { quantity: 2, priceInCents: 1260 },
};

We have to write 2 functions, one that calculates total cost of inventory in cents and the other displays the inventory.

  1. The calculateCartTotal function will take in the cart and return a total price, in cents, of everything inside of it.
  2. The printCartInventory function will take in the cart and return a string, joined by \n, of the quantity and name of each item.

I was able to the finish question one with ease but am struggling with the 2nd one.

1st function:

function calculateCartTotal(cart) {
  let total = 0;
  for(let item in cart){
    const product = cart[item]
    const quantity = product.quantity
    const price = product.priceInCents
    total  = quantity * price
  }
  return total
}

2nd function:

function printCartInventory(cart) {
  let inventory = ""
  for(let item in cart){
    const product = cart[item]
    const quantity = product.quantity
    inventory  = `${quantity}x${product}/n`
  }
  return inventory
}

When I test the 2nd function the autograder gives this error:

expected '2x[object Object]/n1x[object Object]/n1x[object Object]/n3x[object Object]/n' to include '2xCanvas Tote Bag\n1xBlack and White Chuck On Dress\n1xNatural Straw Wide Brim Hat\n3xBlue Stripe Casual Shirt'

CodePudding user response:

When you look at the error message, note the part that says [object Object]. This is part of your code's output, and should ring a bell. It means your code tries to put an object in a string, instead of a string.

The guilty code is here:

inventory  = `${quantity}x${product}/n`

product is not a string, but an object. It is not what you intended to output there. What you want to output is the name of the product, which is the key, not the value associated with that key. So it should be:

inventory  = `${quantity}x${item}/n`
  • Related