Count and Look Up With an Object

In the last lesson, a club member had already counted Maya’s genres for you, and you typed the result in as genreCounts = { "sci-fi": 2, fantasy: 1, memoir: 1 }. That’s fine for four books. The year-end report covers six members and fifteen books, though, so the counting has to come from the reading log itself.

In this lesson, you’ll write a loop that builds that count object from Maya’s books. You’ll also ask an object whether it has a key at all and use a second object to look up a readable label for each genre. You’ll start with the count, filling in an object one book at a time.

Count Genres Into an Object

Counting by hand means going down the list of books and keeping a running number for each genre. A loop can do the same if it has somewhere to keep those numbers, and an object can hold them. Each genre becomes a key, and its value is the number of books counted so far in that genre. An object used like this is called a tally.

Create tally.js with Maya’s record, the same one you wrote in chart.js, and a loop that adds one to her tally for each book:

Language: JavaScript Filename: tally.js
const maya = {
  name: "Maya",
  books: [
    {
      title: "Kindred",
      author: "Octavia E. Butler",
      genre: "sci-fi",
      rating: 5,
      review: "Couldn't put it down.",
    },
    { title: "The Martian", author: "Andy Weir", genre: "sci-fi", rating: 4 },
    {
      title: "Circe",
      author: "Madeline Miller",
      genre: "fantasy",
      rating: 3,
      review: "Slow start, lovely ending.",
    },
    { title: "Educated", author: "Tara Westover", genre: "memoir", rating: 4 },
  ],
};

const counts = {};
for (const book of maya.books) {
  const genre = book.genre;
  counts[genre] = (counts[genre] ?? 0) + 1;
}
console.log(counts);

Run it, and you get the same counts the club member tallied by hand:

Language: Shell
$ node tally.js
{ 'sci-fi': 2, fantasy: 1, memoir: 1 }

The whole tally happens in one line, counts[genre] = (counts[genre] ?? 0) + 1;. It uses brackets because the key is whatever string genre holds. Writing counts.genre would look for a key literally named "genre". The tally starts as an empty object, {}, so it has no keys until the loop adds them.

That’s why the line needs ?? 0. On the first pass, the book is Kindred, and counts["sci-fi"] doesn’t exist yet, so reading it gives undefined.

The nullish coalescing operator, ??, gives you its right side when its left side is null or undefined, and its left side otherwise. So the first pass computes 0 + 1 and stores 1 under "sci-fi". On the second pass, the loop finds 1 for The Martian, and ?? keeps it, so the count becomes 2.

Watch out: if you leave out the starting value and write counts[genre] = counts[genre] + 1, the first pass computes undefined + 1, which is NaN, and every count in the tally ends up as NaN.

If the tally line still feels dense, the mentor can trace it with you. Clicking the button opens a chat with this question and the line attached:

Check Whether a Key Is There

The tally only has keys for genres Maya read. For every member, the report has to answer questions like this: Did Maya read any mystery books or any memoirs? Reading counts.mystery gives undefined, but that only tells you about the value. You want to know whether the key exists.

JavaScript has two ways to ask that. Object.hasOwn() takes an object and a key and returns true if the object has that key as its own property.

The in operator asks a similar question, putting the key first, but has one difference you’ll see in the last line. Start Node’s REPL with node and try both on Maya’s tally:

Language: JavaScript
> const counts = { "sci-fi": 2, fantasy: 1, memoir: 1 };
undefined
> Object.hasOwn(counts, "memoir")
true
> Object.hasOwn(counts, "mystery")
false
> "mystery" in counts
false
> "toString" in counts
true

The last line shows how they differ. An object created with {} inherits a few properties it didn’t define, such as toString, and in counts those too. Object.hasOwn() only looks at the object’s own properties, the keys you put in it, so it’s the one to use on a tally or a lookup table. That’s all you need about inherited properties for now. In older code, you’ll also see counts.hasOwnProperty("memoir"), which asks the same question.

Now say the report should list every club genre for each member, zeros included. The ??= operator assigns only when the current value is null or undefined, so it fills an absent count but keeps a real 0. The delete operator removes a key. Try them on a fresh copy of Maya’s tally, in the same REPL session:

Language: JavaScript
> const fullCounts = { "sci-fi": 2, fantasy: 1, memoir: 1 };
undefined
> fullCounts.mystery ??= 0;
0
> fullCounts.fantasy ??= 0;
1
> fullCounts
{ 'sci-fi': 2, fantasy: 1, memoir: 1, mystery: 0 }
> Object.hasOwn(fullCounts, "mystery")
true
> delete fullCounts.mystery
true
> fullCounts
{ 'sci-fi': 2, fantasy: 1, memoir: 1 }

The first ??= added mystery: 0, and the second left Maya’s fantasy count of 1 alone. After delete, the key is gone.

Watch out: a check like if (fullCounts.mystery) asks whether the value is truthy, not whether the key is there. A key that holds 0, "", or false looks missing, and filling gaps with ||= instead of ??= would overwrite a real 0 with your default.

A zero count is exactly where that difference bites in a real report. The mentor can give you a few quick cases to decide:

Look Up Labels by Genre

The tally’s keys are short codes like "sci-fi", but a report could say “Science fiction” instead. You can keep the readable labels in a second object, with one key per genre code. An object used to find a value from a key in your data is called a lookup table.

A lookup table looks like a record, but it does a different job. A record such as a book describes one thing. You know its property names when you write the code, so you read them with a dot: book.title. A lookup table holds many entries of the same kind, and the key you need comes from the data while the program runs, so you read it with brackets: genreLabels[genre].

Leave the REPL with .exit to get back to your terminal. Then add the club’s labels to the end of tally.js, with a loop over the tally’s entries that collects each label with its count:

Language: JavaScript
const genreLabels = {
  "sci-fi": "Science fiction",
  fantasy: "Fantasy",
  memoir: "Memoir",
  mystery: "Mystery",
  fiction: "Fiction",
};

const labeled = [];
for (const [genre, count] of Object.entries(counts)) {
  labeled.push([genreLabels[genre], count]);
}
console.log(Object.fromEntries(labeled));

The table has a label for each of the club’s five genres, including two Maya didn’t read. That’s fine, because the loop only looks up the genres in her tally.

Each pass pushes a two-item array containing a label and a count, matching the shape of the entries Object.entries() gave you. Object.fromEntries() goes the other way. It takes an array of [key, value] pairs and builds an object from them, so the report gets an object it can keep working with.

Your file should now hold Maya’s record, the tally, and the lookup:

Language: JavaScript Filename: tally.js
const maya = {
  name: "Maya",
  books: [
    {
      title: "Kindred",
      author: "Octavia E. Butler",
      genre: "sci-fi",
      rating: 5,
      review: "Couldn't put it down.",
    },
    { title: "The Martian", author: "Andy Weir", genre: "sci-fi", rating: 4 },
    {
      title: "Circe",
      author: "Madeline Miller",
      genre: "fantasy",
      rating: 3,
      review: "Slow start, lovely ending.",
    },
    { title: "Educated", author: "Tara Westover", genre: "memoir", rating: 4 },
  ],
};

const counts = {};
for (const book of maya.books) {
  const genre = book.genre;
  counts[genre] = (counts[genre] ?? 0) + 1;
}
console.log(counts);

const genreLabels = {
  "sci-fi": "Science fiction",
  fantasy: "Fantasy",
  memoir: "Memoir",
  mystery: "Mystery",
  fiction: "Fiction",
};

const labeled = [];
for (const [genre, count] of Object.entries(counts)) {
  labeled.push([genreLabels[genre], count]);
}
console.log(Object.fromEntries(labeled));

Run the script again, and the tally comes first, then the same counts under their labels:

Language: Shell
$ node tally.js
{ 'sci-fi': 2, fantasy: 1, memoir: 1 }
{ 'Science fiction': 2, Fantasy: 1, Memoir: 1 }

The counts didn’t change, but their keys did. You took the tally apart into entries, swapped each genre code for the label the lookup table found, and built a new object from the pairs. The original counts object is untouched.

Check Your Understanding

Jamal read three books this year, with these genres:

Language: JavaScript
const jamalGenres = ["mystery", "memoir", "mystery"];

Start the REPL again with node to try these, but answer the first before you run anything:

  1. A friend tallies Jamal’s genres with counts[genre]++ inside the loop, starting from const counts = {};. What does console.log(counts) print, and what’s the fix?
  2. Write a loop that tallies Maya’s ratings, [5, 4, 3, 4], into an object, and run it.
  3. Jamal’s tally ends up as { mystery: 2, memoir: 1, fantasy: 0 }. Write a check for whether it has a fantasy key, and explain why if (counts.fantasy) would give the wrong answer.

For the first, every count comes out as NaN, because the first ++ on each genre adds 1 to undefined. The NaN right under the loop is the REPL showing the last value the loop’s body computed, and you can ignore it, as you can the 2 under the next loop:

Language: JavaScript
> const jamalCounts = {};
undefined
> for (const genre of ["mystery", "memoir", "mystery"]) {
…   jamalCounts[genre]++;
… }
NaN
> jamalCounts
{ mystery: NaN, memoir: NaN }

The fix is the starting value: counts[genre] = (counts[genre] ?? 0) + 1;.

For the second, the tally line works on the ratings with ratingCounts and rating in place of counts and genre. They become string keys, and as you saw in the last lesson, small whole-number keys like these come back first, in ascending order:

Language: JavaScript
> const ratingCounts = {};
undefined
> for (const rating of [5, 4, 3, 4]) {
…   ratingCounts[rating] = (ratingCounts[rating] ?? 0) + 1;
… }
2
> ratingCounts
{ '3': 1, '4': 2, '5': 1 }

An object tally works for values like these. Its keys become strings, though, so 1 and "1" would share a count, and an inherited name such as "toString" doesn’t start out undefined. Later in the course, you’ll use Map to avoid both issues.

For the third, Object.hasOwn(counts, "fantasy") returns true, because it asks about the key. if (counts.fantasy) asks about the value, and 0 is falsy, so it would skip its body as if the key weren’t there.

You can now build a tally from a list of records, look up values by key, and check whether a key exists before you rely on it. Next, in Exercise: Chart and Tally a Member’s Books, you’ll write functions that print a member’s star chart, list pairs of their books, tally their genres, and look up the genre labels.

It’s the course’s first coding exercise. You write code right in the browser, and Run Tests checks it with automated tests that show what passes and what fails. Run them early and often, and read a failing test’s message or an error for a clue to what to change next. Full screen gives you more room to code.

Become a Member to join the conversation.