Looping Through Arrays of Objects

Arrays of objects are usually processed with a loop. In a for...of loop, the loop variable holds one whole object in each iteration, so you read its properties with a dot:

const pets = [
    { name: "Rex", species: "dog", age: 3 },
    { name: "Bella", species: "cat", age: 2 },
    { name: "Kiwi", species: "parrot", age: 4 }
];

for (const pet of pets) {
    console.log(`${pet.name} is a ${pet.species}.`);
}
Rex is a dog.
Bella is a cat.
Kiwi is a parrot.

In the first iteration, pet holds Rex's object, in the second Bella's, in the third Kiwi's. It's a good habit to name the array in the plural and the loop variable in the singular (pets, pet). The code then reads almost like a sentence: for each pet of the pets.

The patterns from the lesson on loops work here too. To add up the ages of all the pets, add one pet's age in each iteration:

let totalAge = 0;
for (const pet of pets) {
    totalAge += pet.age;
}
console.log("Total age:", totalAge);
Total age: 9

And with an if inside the loop, you can pick only some of the objects, for example the pets older than 2:

for (const pet of pets) {
    if (pet.age > 2) {
        console.log(pet.name);
    }
}
Rex
Kiwi

A typical mistake is to forget the property: totalAge += pet; adds the whole object instead of its age. The result isn't a number but a strange text like 0[object Object][object Object][object Object].

Instructions

Write a for...of loop that goes through cart and prints the name and price of each item, separated by a colon, for example Dog food: 250.

Below, add up the prices of all items and print the result as Total: 535.

Finally, print the names of the items that cost less than 100, each on its own line.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/9