In the overview, you watched Sam’s recipe box lose every new recipe on a reload, then saw the finished box come back with its recipes intact, even after a bad save. Making the box remember starts with the data it has to save, which is an array of recipe objects, each with its own properties.
To check, save, and rebuild data like that, your code has to work through an object’s properties without naming each one by hand. In this lesson, you’ll loop over an object’s keys, its values, or both, and you’ll see what each of the three Object functions gives you.
Start With Sam’s Recipe Box
Sam’s recipe box is a page that holds the family’s recipes. A form adds a recipe, a Filter box finds one by name, and a Delete button asks before it removes anything. Behind the page, the recipes sit in one array, and a render() function redraws the list from that array after every change. However, the array lives only as long as the tab. Reload, and the five starting recipes come back while everything Sam added is gone.
That’s the problem this course solves. Any app that people open more than once faces it, because they expect their to-do lists, budgets, or game high scores to be there tomorrow. By the end of the course, Sam’s box will save itself after every change and load what it saved on every visit. It will also keep working when the save is missing, corrupt, or written by an older version of the app.
You’ll get there in steps. First, you’ll work with objects and nested data, because each recipe is about to gain a list of ingredients, and restored data has to be checked field by field. Then you’ll turn data into text and keep it in the browser. After that, you’ll handle saves that fail or come back broken. Finally, a project brings the pieces together in the recipe box.
This course assumes you know the JavaScript basics, including objects and arrays of objects, and that you’ve built a page that redraws itself from an array and reads a form.
Type along with text lessons like this one, and watch the videos for what moves on the page. Each section ends with an exercise you solve in the browser, with tests that check your code. Buttons in the lessons open a conversation with the AI mentor when you want practice or another explanation.
You don’t need Sam’s files for this lesson. Open a new tab, go to about:blank, and open the Console with Ctrl+Shift+J, or Cmd+Option+J on macOS. Type each entry rather than pasting it. As a safety measure, Chrome may block pasting into the Console in a browser profile with little Console history. Press Shift+Enter between the lines of an entry.
Start with Grandma Ines’s lentil soup as the recipe box stores it, with an ID like the ones crypto.randomUUID() makes:
> const soup = {
… id: "3b9e6f0a-5c1d-4f8e-9a27-6d4c8b1e2f70",
… name: "Grandma Ines's lentil soup",
… servings: 6,
… minutes: 45,
… category: "soup",
… vegetarian: true,
… };
undefined
The Console answers undefined because a const declaration has no value to show. The recipe is now stored in soup, ready to explore.
List a Recipe’s Fields
Say you want to log every field of a recipe, perhaps to see what a save brought back. You could write six console.log() calls, one per property name. However, that code goes out of date the moment a recipe gains a property, and the ingredients are coming soon. You need the property names as data that your code can loop over.
The names of an object’s properties are its keys. The Object.keys() function takes an object and returns an array of its keys:
> Object.keys(soup)
(6) ['id', 'name', 'servings', 'minutes', 'category', 'vegetarian']
The (6) is Chrome’s count of the items in the array. Every key comes back as a string, and named keys like these appear in the order the properties were written.
Why not loop over soup itself? An array gives for...of its items one at a time. A plain object could give its keys, its values, or both, and none of them is the clear default. The Object functions make you choose, and each choice comes back as an ordinary array.
The loop below logs each key with its value. The key is in the variable field, so you read the value with brackets. soup[field] looks up whatever name field holds on this pass, while soup.field would look for a property literally named field, which the recipe doesn’t have:
> for (const field of Object.keys(soup)) {
… console.log(`${field}: ${soup[field]}`);
… }
id: 3b9e6f0a-5c1d-4f8e-9a27-6d4c8b1e2f70
name: Grandma Ines's lentil soup
servings: 6
minutes: 45
category: soup
vegetarian: true
undefined
On the first pass, field holds "id", and soup[field] reads the ID. On the next pass, it holds "name", and so on through all six keys. The final undefined is the Console’s own echo after the loop finishes, not a line the loop logged.
You can confirm that the loop follows the data. Type soup.rating = 5;, press Up until the loop comes back, press Enter to run it again, and a seventh line, rating: 5, appears without any change to the loop.
Watch out for keys that are whole numbers, such as the years in { 2019: "Banana bread", 1987: "Lentil soup" }. Object.keys() gives them back as strings, sorted in ascending order and ahead of every other key, whatever order you wrote them in.
To make sure the keys and the brackets have clicked, use the next button to open a conversation with the AI mentor. The mentor shows you one example at a time, with a small object and a line of code. You predict what the line returns or logs, and the mentor tells you whether you’re right and why:
Choose Keys, Values, or Entries
Keys answer the question “Which fields are there?” Other tasks need something else. Sam’s box will soon show how many recipes it holds in each category. An object will store these counts, with a category as each key and a count as its value:
> const counts = { soup: 1, main: 2, baking: 1, dessert: 1 };
undefined
These counts match the five recipes in the box. You’ve typed them in by hand for now, and you’ll work them out from the recipes in the following lesson.
To get the total number of recipes, you don’t need the category names at all, only the numbers. Object.values() returns an array of an object’s values, in the same order as its keys. Add them up with a running total, as you would for any array of numbers:
> let total = 0;
undefined
> for (const count of Object.values(counts)) {
… total = total + count;
… }
5
This time the Console echoes 5 after the loop, because the loop logs nothing and the Console shows the last value computed inside it, which is the final total. With four categories, you could add 1 + 2 + 1 + 1 in your head. However, the loop gives the right answer for forty categories too, and for counts your code calculates for you.
To log a line per category, such as main: 2, each pass needs a key and its value together. Object.entries() returns both, as an array of entries: one small array per property, holding that property’s key and its value. Here’s the first entry. As you type it, the Console previews the result in gray:
> Object.entries(counts)[0]
(2) ['soup', 1]
The first entry is a two-item array, with the key first and the value second. Therefore, inside a loop over the entries, entry[0] is the category and entry[1] is its count:
> for (const entry of Object.entries(counts)) {
… console.log(`${entry[0]}: ${entry[1]}`);
… }
soup: 1
main: 2
baking: 1
dessert: 1
undefined
You could write the same loop with Object.keys() and counts[category]. Object.entries() saves that lookup when every pass needs both halves. Which of the three you pick depends on what the loop’s body needs:
- Use
Object.keys()when you need the names, such as checking which fields a recipe has. You can still read each value with brackets. - Use
Object.values()when only the values matter, such as adding up counts. - Use
Object.entries()when every pass uses a key and its value together, such as writingmain: 2. MDN’s page onObject.entries()shows more ways to use the pairs.
To practice choosing, use the next button to ask the AI mentor to describe small tasks on Sam’s recipes, one at a time. You say which function you’d use and why, and the mentor tells you whether it fits the task:
You can now loop over the keys, values, or entries of data objects like these. The three functions list an object’s own properties, the ones written into it. Objects can have other kinds of properties that these functions skip, but that’s all you need about them for now.
However, you typed the counts object in by hand, and it’ll be wrong as soon as Sam adds a sixth recipe. In Count and Look Up With an Object, you’ll build counts like these as your code loops over the recipes, and you’ll use an object to look up values by name.