01 / 04
Loops, and where your data lives
INPUT · Slides
Running a loop over the nesting
02 / 04
Use i as the number
Use the i from your for as the array number and join .name onto the end.
Read list[i].name as "the name of entry i".
const pets = [ { name: "Mofu", age: 3 }, { name: "Pochi", age: 5 }, { name: "Tama", age: 1 },];for (let i = 0; i < pets.length; i++) { console.log(pets[i].name);}Result
Mofu Pochi Tama
03 / 04
Catching one at a time reads better
When pets[i].name turns up over and over it gets hard to read. Catch it once inside the { } and it reads far better.
Either way behaves the same. Choose whichever reads better.
const pets = [ { name: "Mofu", age: 3 }, { name: "Pochi", age: 5 },];for (let i = 0; i < pets.length; i++) { const pet = pets[i]; console.log(`${pet.name}: age ${pet.age}`);}Result
Mofu: age 3 Pochi: age 5
04 / 04
Adding it all up
Put the piling variable outside and you get the total across every entry. However many there are, the code is the same.
Mix in an if and you can "count only the ones that match". This is where every tool you have learned joins up.
const cart = [ { name: "bread", price: 160, count: 2 }, { name: "seaweed", price: 220, count: 3 },];let total = 0;for (let i = 0; i < cart.length; i++) { total += cart[i].price * cart[i].count;}console.log(total);Result
980