Code / JavaScript from Zero / Unit 4: Objects and functions

Arrays of objects ऑब्जेक्ट के ऐरे

Lesson 10 of 15 · about 14 minutes · A shopping cart total and a stock list.

⚡ 0 XP

Step 1 of 2

A shopping cart

name"Asha"class9city"Surat"

Real apps keep arrays of objects: each item in a cart is an object, and the cart is an array of them.

  • cart[0].name is the first item’s name
  • for (const item of cart) { ... } visits each object; inside, use item.price and item.qty

Wrap the work in a function that takes the cart as a parameter — then it works for any cart.

Example
const order = [
  { name: "Idli", price: 40, qty: 2 },
  { name: "Filter coffee", price: 25, qty: 1 },
];
for (const item of order) {
  console.log(`${item.name}: ₹${item.price * item.qty}`);
}

🎯 Challenge: Kirana cart total +20 XP

Complete cartTotal(items) so it returns the sum of price × qty for every item. For the given cart it returns 1110, and for an empty cart [] it returns 0. Then print Cart total: ₹1110.

Try twice to unlock the solution (0/2)

script.jsCtrl ⏎
Console

Output from console.log appears here.

Checklist

Press Run to check your code.

  • cartTotal(cart) is 1110
  • Works for another cart and an empty cart
  • The console shows “Cart total: ₹1110”
Lesson notes (text version)

1. A shopping cart

Real apps keep arrays of objects: each item in a cart is an object, and the cart is an array of them.

  • cart[0].name is the first item’s name
  • for (const item of cart) { ... } visits each object; inside, use item.price and item.qty

Wrap the work in a function that takes the cart as a parameter — then it works for any cart.

                const order = [
  { name: "Idli", price: 40, qty: 2 },
  { name: "Filter coffee", price: 25, qty: 1 },
];
for (const item of order) {
  console.log(`${item.name}: ₹${item.price * item.qty}`);
}
              

Challenge: Kirana cart total

Complete cartTotal(items) so it returns the sum of price × qty for every item. For the given cart it returns 1110, and for an empty cart [] it returns 0. Then print Cart total: ₹1110.

2. filter and map on objects

filter and map shine with arrays of objects. You can even chain them — the result of one goes into the next:

products.filter(p => p.stock > 0).map(p => p.name)

First keep the products in stock, then turn each product into just its name.

                const trains = [
  { name: "Rajdhani", late: 0 },
  { name: "Shatabdi", late: 15 },
];
console.log(trains.filter(t => t.late > 0).map(t => t.name)); // ["Shatabdi"]
              

Challenge: What can we sell today?

Write two functions that take a list of fruit objects:

  • inStockNames(list) returns the names of fruits whose stock is more than 0
  • priceTags(list) returns a tag for every fruit like Mango: ₹120

Search by task, format or tool name.