In the last video, you looped over maya.books, an array of Maya’s book records, to print a line of stars for each book and to pair her books up. The year-end report needs more than that, though. It needs to say how many books Maya read in each genre, and that kind of count lives in an object, with one property per genre.
In this lesson, you’ll loop over an object instead of an array. You’ll get an object’s keys, its values, or both as an array you can loop over, choose the one your loop needs, and predict what each call gives back. Start by getting the object’s property names.
Get the Keys as an Array
Say a club member has tallied Maya’s year by hand: two sci-fi books, one fantasy, and one memoir.
In the next lesson, you’ll build this object from her books with a loop. For now, it’s a plain object you type in, genreCounts = { "sci-fi": 2, fantasy: 1, memoir: 1 }, where each key is a genre and each value is how many books Maya finished in it.
The for...of loop you used on maya.books is the natural first try. However, for (const genre of genreCounts) stops with TypeError: genreCounts is not iterable, because for...of needs an iterable, a value it can step through item by item. Arrays are iterable, but a plain object isn’t.
The fix is to turn the object’s keys into an array first. Object.keys() takes an object and returns a new array of the object’s own property names, such as the ones you wrote in its literal. Create genres.js with Maya’s counts and loop over that array:
genres.js
const genreCounts = { "sci-fi": 2, fantasy: 1, memoir: 1 };
const genres = Object.keys(genreCounts);
console.log("Genres:", genres);
for (const genre of genres) {
console.log(`${genre}: ${genreCounts[genre]}`);
}
Run it, and you get the array first, then one line per genre:
$ node genres.js
Genres: [ 'sci-fi', 'fantasy', 'memoir' ]
sci-fi: 2
fantasy: 1
memoir: 1
The keys come back in the order you wrote them, as an ordinary array of strings.
Inside the loop, genreCounts[genre] reads the count. The square brackets use the value of the variable genre as the property name. Writing genreCounts.genre would look for a property literally called genre and give undefined. The "sci-fi" key needs quotes in the object because of its hyphen, and you have to read it with brackets, not a dot.
Choose Keys, Values, or Entries
Looping over the keys and reading each value works, but it isn’t always what the task needs. Sometimes you only care about the numbers, and sometimes you want each name and its number together without the extra lookup. Two more methods on Object cover those cases:
Object.values()returns an array of the values of those same properties, without their keys.Object.entries()returns an array of entries, where each entry is a two-item array for one of those properties: the key, then its value.
Replace everything after the object in genres.js with a total and a loop over the entries:
genres.js
const genreCounts = { "sci-fi": 2, fantasy: 1, memoir: 1 };
let total = 0;
for (const count of Object.values(genreCounts)) {
total += count;
}
console.log(`Books in total: ${total}`);
console.log("Entries:", Object.entries(genreCounts));
for (const [genre, count] of Object.entries(genreCounts)) {
console.log(`${genre}: ${count} of ${total}`);
}
Run the script again, and each loop gets exactly what it needs:
$ node genres.js
Books in total: 4
Entries: [ [ 'sci-fi', 2 ], [ 'fantasy', 1 ], [ 'memoir', 1 ] ]
sci-fi: 2 of 4
fantasy: 1 of 4
memoir: 1 of 4
The total doesn’t care which genre a count belongs to, so Object.values() hands the loop only the numbers. The second loop needs each genre and its count. The logged entries show that it receives an array of small arrays, each holding one of those pairs.
The loop’s header unpacks each entry with the array destructuring you’ve used before, which picks values by position. On the first pass, the entry is ['sci-fi', 2], so genre gets 'sci-fi' from position 0 and count gets 2 from position 1. The loop repeats that unpacking for each entry.
Before any loop over an object, ask what its body needs. For the names alone, use Object.keys(), and for the numbers alone, use Object.values(). When the body needs both, use Object.entries() and unpack each pair.
If the destructured loop header still looks dense, the mentor can take it apart with you. The button opens a chat with this question and the loop header attached:
Use Numbers as Keys
The genre keys were strings anyway, so their type never showed. Maya also tallies how many books she gave each rating, and ratings are numbers. She wrote her best rating first: one book got a 5, two got a 4, and one got a 3.
What happens to keys like these when you ask for them back? Find out in Node’s REPL, an interactive JavaScript prompt you start with node and no filename. Type Maya’s rating tally, then ask for its keys and add 1 to the first one:
> const ratingCounts = { 5: 1, 4: 2, 3: 1 };
undefined
> Object.keys(ratingCounts)
[ '3', '4', '5' ]
> Object.keys(ratingCounts)[0] + 1
'31'
The keys came back as '3', '4', and '5', in quotes, because an object’s property names are always strings. When you write 5: in the literal, JavaScript turns it into the key '5', and Object.keys() hands back what’s there.
The keys also came back sorted, not in the order Maya wrote them: small whole-number keys like these come first, in ascending order. The exact rule has a few edge cases, but that’s the one you’ll meet.
Adding 1 to the string '3' joins text, so you get '31', not 4.
So when you need a number-like key as a number, convert it with Number(key), and don’t expect number-like keys to come back in the order you added them. When the order matters, as with rankings or places in a list, keep the values in an array instead.
Later in the course, you’ll meet Map, which keeps its keys’ types and the order you added them in. That’s all you need about it for now.
The string keys are the part that slips past you in a real program, because nothing fails until a sum comes out as text. Ask the mentor to test you on it:
Check Your Understanding
Jamal has two tallies for his year, one by genre and one by rating:
const jamalGenres = { mystery: 2, memoir: 1 };
const jamalRatings = { 5: 1, 3: 1, 4: 1 };
Work through these before you run anything:
- Predict what
Object.values(jamalGenres),Object.entries(jamalGenres), andObject.keys(jamalRatings)return. - Jamal wants a line per genre in the form
mystery: 2 books. Which of the three methods fits, and how would you write the loop? - A friend writes
for (const genre of jamalGenres)to print the genres. What happens, and what’s the smallest change that makes it work?
For the first, the genre tally keeps the order Jamal wrote it in, while the rating keys come back sorted and as strings:
> const jamalGenres = { mystery: 2, memoir: 1 };
undefined
> Object.values(jamalGenres)
[ 2, 1 ]
> Object.entries(jamalGenres)
[ [ 'mystery', 2 ], [ 'memoir', 1 ] ]
> const jamalRatings = { 5: 1, 3: 1, 4: 1 };
undefined
> Object.keys(jamalRatings)
[ '3', '4', '5' ]
For the second, the line needs both the genre and its count, so use Object.entries() and unpack each entry in the loop’s header:
for (const [genre, count] of Object.entries(jamalGenres)) {
console.log(`${genre}: ${count} books`);
}
For the third, the loop stops with TypeError: jamalGenres is not iterable, because a plain object isn’t iterable. Looping over Object.keys(jamalGenres) instead gives for...of the array of genre names it needs.
You can now loop over an object’s keys, values, or entries and pick the one the task needs. So far, someone else counted Maya’s genres for you. In the next lesson, Count and Look Up With an Object, you’ll build that count object yourself from her books.