In this video, you found how much onion Grandma Ines’s lentil soup needs by following a path into Sam’s recipes, one level at a time. Here are the key points:
- Sketch the shape before you write a path. Sam’s recipes are nested data: an array of recipe objects, each with an
ingredientsarray of ingredient objects. Arrays and objects take turns, four levels deep. - Each step of a path goes down one level. An array level takes square brackets and an index, such as
[1], and indexes count from zero. An object level takes a dot and a key, such as.amount, or the key in square brackets, as with Sam’s pantry. - Read a path from left to right against the sketch. In
recipes[0].ingredients[2].unit,[0]reaches the soup,.ingredientsits list,[2]the third ingredient, the stock, and.unitits unit. - Watch out for a path that skips a level.
recipesis an array, sorecipes.ingredientsisundefined, and the next step throws aTypeError. In Chrome, its message names the step after the undefined one,(reading '1'), so the fix goes before.ingredients: the recipe’s index, as inrecipes[0].ingredients[1].amount.
Here’s how the soup’s record looks once Sam’s box keeps ingredients, a change the box gets later in the course, followed by the two paths from the video:
const recipes = [
{
id: "b5115c00-be61-4769-919a-67688c8be942",
name: "Grandma Ines's lentil soup",
servings: 6,
minutes: 45,
category: "soup",
vegetarian: true,
ingredients: [
{ name: "lentils", amount: 200, unit: "g" },
{ name: "onion", amount: 1, unit: "whole" },
{ name: "stock", amount: 1, unit: "l" },
],
},
// ...Sam's other four recipes, the same shape
];
console.log("Onion:", recipes[0].ingredients[1].amount);
console.log("Unit:", recipes[0].ingredients[2].unit);
Save and reload the page, and the Console shows the onion’s amount and the stock’s unit: