Arrays of Objects

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — The Shape of Real Data

Imagine storing your battle team when each Codémon has its own name, type, and level. In real programs, almost every collection of data takes this shape: an array holding the list, and an object describing each item:

const team = [ { name: "Aquachu", type: "water", level: 12 }, { name: "Pyrochu", type: "fire", level: 8 }, { name: "Zap", type: "electric", level: 4 } ]; console.log(team.length); console.log(team[0].name);

To read any piece of data, follow the path from left to right: the square brackets `[0]` select which element in the array, and the dot `.name` selects which property of that object.

Exercise 2 — Looping Over the Objects

Because `team` is still a regular array, every loop and array method (`forEach`, `map`, `filter`...) works normally. On each turn, the callback receives a whole object:

const team = [ { name: "Aquachu", level: 12 }, { name: "Zap", level: 4 } ]; team.forEach((cdm) => { console.log(cdm.name + " Lv." + cdm.level); });

Even better: you can destructure each object right inside the callback parameter to access its properties directly:

const team = [ { name: "Aquachu", level: 12 }, { name: "Zap", level: 4 } ]; team.forEach(({ name, level }) => { console.log(name + " Lv." + level); });

Exercise 3 — Quiz: Reach the Detail

What does this code print?

const shop = [ { name: "Potion", price: 30 }, { name: "Elixir", price: 120 } ]; console.log(shop[1].price);
Options
• 120
• 30
• "Elixir"
• undefined

Hint : Pick the element first, then the property.

Exercise 4 — Second Member's Name

Print the name of the second Codémon.

Hint : One pair of symbols selects by position, another selects by key.

Exercise 5 — Adding and Removing Items

The items are objects, but the array is still an array: `push`, `pop` and the others work exactly as usual. You just push a whole object:

const team = [ { name: "Aquachu", level: 12 } ]; team.push({ name: "Metachu", level: 15 }); console.log(team.length); console.log(team[1].name);

Careful with one thing: the objects inside are shared by reference. Modifying `team[0].level` changes the object for everyone holding it.

const team = [ { name: "Aquachu", level: 12 } ]; const first = team[0]; first.level = 20; console.log(team[0].level);

Exercise 6 — Quiz: Shared Object

What does this code print?

const team = [{ hp: 40 }]; const cdm = team[0]; cdm.hp = 5; console.log(team[0].hp);
Options
• 5
• 40
• undefined
• An error

Hint : Reading an element doesn't make a copy of it.

Exercise 7 — Counting and Summing

When you have an array of objects, you often need to calculate a total across the whole list — for example, your team's combined HP. Start a variable at `0`, then loop through the array and add each object's property with `+=`:

const team = [ { name: "Aquachu", hp: 40 }, { name: "Pyrochu", hp: 0 }, { name: "Zap", hp: 25 } ]; let totalHP = 0; team.forEach((cdm) => { totalHP += cdm.hp; }); console.log("Total HP: " + totalHP);

The exact same pattern lets you count how many objects match a condition: combine a counter variable with an `if` check inside the loop:

const team = [ { name: "Aquachu", hp: 40 }, { name: "Pyrochu", hp: 0 }, { name: "Zap", hp: 25 } ]; let ready = 0; team.forEach((cdm) => { if (cdm.hp > 0) { ready++; } }); console.log("Ready to battle: " + ready);

Exercise 8 — Total Level

Add up every level into `total`.

Hint : Accumulate rather than replace, and read the right property of each object.

Exercise 9 — Quiz: The Whole Object

In `team.forEach((cdm) => ...)`, what is `cdm` at each turn?

Options
• One object of the array
• The index of the object
• The name property
• The whole array

Hint : The callback receives the elements themselves, whatever they are.

Exercise 10 — Two Levels, Two Tools

`const team = [{ name: "Zap" }];`. Match each expression with what it gives.

Items to match
• team.length
• team[0]
• team[0].name
• team[5]
Definitions
• The number of objects
• The first object
• A property of the first object
• undefined

Exercise 11 — Gym Roster

The gym keeps its fighters as a list of objects. Produce its daily report.

Step 1: print `"Fighters: N"` with the number of entries. Step 2: print one line per fighter, in the format `"name (type) Lv.X"`. Step 3: while looping, count how many are level 10 or more, and add up all the levels. Step 4: print `"Veterans: N"` and `"Average level: X"`, the average being the total divided by the number of fighters.

Expected output:

Fighters: 4 Aquachu (water) Lv.12 Pyrochu (fire) Lv.8 Zap (electric) Lv.4 Metachu (metal) Lv.16 Veterans: 2 Average level: 10
Starter code
const gym = [ { name: "Aquachu", type: "water", level: 12 }, { name: "Pyrochu", type: "fire", level: 8 }, { name: "Zap", type: "electric", level: 4 }, { name: "Metachu", type: "metal", level: 16 } ]; // Write your code here
Back to the course