Skip to content

Instantly share code, notes, and snippets.

@frankstepanski
Last active March 9, 2022 02:26
Show Gist options
  • Save frankstepanski/44acf02b7b971f19aca72bf8c787b190 to your computer and use it in GitHub Desktop.
Save frankstepanski/44acf02b7b971f19aca72bf8c787b190 to your computer and use it in GitHub Desktop.
JavaScript foundations: Looping over objects
const cart = {
"Gold Round Sunglasses": { quantity: 1, priceInCents: 1000 },
"Pink Bucket Hat": { quantity: 2, priceInCents: 1260 },
};
// The calculateCartTotal function will take in the cart and return a total price, in cents, of everything inside of it.
function calculateCartTotal(cart) {
let grandTotal = 0;
for (const prop in cart) {
let quantity = Object.values(cart[prop])[0];
let price = Object.values(cart[prop])[1];
grandTotal += quantity * price;
}
return grandTotal;
}
// The printCartInventory will take in the cart and return a string, joined by \n, of the quantity and name of each item.
function printCartInventory(cart) {
let inventory = "";
for (const prop in cart) {
inventory += `${Object.values(cart[prop])[0]}x${prop}\n`
}
return inventory;
}
console.log(calculateCartTotal(cart));
console.log(printCartInventory(cart));
@KarolinaFlores
Copy link

thank you

@SolidFox-ZL
Copy link

very cool I got it to loop but it wasn't not looping while adding the quantity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment