In this lesson, the year-end report moved from Maya alone to the whole Riverside Book Club. You drew the club’s log one level at a time, traced a path down the drawing to a single rating, read the error a broken path gives, and saw why each level is an array or an object.
Key Points
- When you print nested data with
console.log(), Node only goes so deep. It shows each member’s name and books list, but every book shows up as[Object], so draw the shape yourself to see every level, and read the bottom level, the book records, from the file. - The log has four levels:
logis an array of members, each member is a plain object with anameandbooks,booksis an array, and each book is a plain object with atitle, anauthor, agenre, aratingand sometimes areview. Luis joined in December, so Luis’sbooksarray is empty. - A path takes one step per level: an index in brackets for an array, a property name after a dot for an object.
log[1].books[0].ratinggoes to Jamal’s record, then his books, then his first book, The Thursday Murder Club, then its rating,5.log[2].books[1].titleis the second book in Rosa’s list,"Little Fires Everywhere". - When a step in the middle of a path doesn’t match the shape, it gives
undefined, and the step after it throws.log[1].book[0].ratingstops withTypeError: Cannot read properties of undefined (reading '0'). The message names the step JavaScript was trying to take,0, so the step right before it,.book, is the broken one. A member hasbooks, with an s. - Watch out for a path that skips a level.
logis an array, solog.booksisundefined, andlog.books[0]throws. Start with an index, such aslog[1]. - The members are an array because they’re many things of the same kind, and the report goes through all of them in order. To look members up by name, a lookup table would fit instead, like the genre labels. Each member is an object because its parts are different things, reached by name.
member.namesays what it holds, andmember[0]doesn’t. The same holds one level down forbooksand each book.
Final Code
The script report.js holds the club’s full log and reads two values from it. Copy it to follow along with the video: