JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 8: Objects and Structured DataLesson 38 of 150About 45 minutes

Lesson 38: Nested objects and arrays

01Opening question

An order has a customer, an address, and a list of items, each with its own price. How do you reach "the price of the second item" in data like that?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Read a path one step at a time: order → items → [1] → price.

const order = {
  id: 1042,
  customer: { name: "Ada", address: { city: "London" } },
  items: [{ name: "Mug", price: 8 }, { name: "Tea", price: 5 }]
};
console.log(order.customer.address.city);
console.log(order.items[1].price);

03Objective and prerequisites

Learning objective: Read and update nested objects and arrays, follow a path step by step, loop over nested collections, and print nested data clearly.

You need: Lesson 37: Properties, methods and dynamic keys, Lesson 29: Iterating over collections

Skills practised: Objects, Nested data.

04Explanation

Real data is nested: objects inside objects, arrays inside objects, objects inside arrays.

Follow a path one step at a time, using .key for objects and [index] for arrays: order.items[1].price.

When a path fails, log each step (order, then order.items, then order.items[1]) to find the first one that is undefined.

Loop over a nested array with for...of and read properties of each element; use nested loops for arrays inside arrays.

05Definitions

Nested object
An object stored as a property value inside another object.
Path
The sequence of keys and indexes that leads to a value, such as order.items[0].price.
Array of objects
A list whose elements are objects, the most common shape of app data.
JSON
A text format for nested data, using object and array syntax.
Accessor function
A small function that reads a value from a known place in a data structure.

Open the full glossary

06Visual learning object

Nested object explorer. See every path in a nested object, such as order.items[0].price, with the value at the end of it.

Loading the interactive object…

Open the full Nested object explorer page with its guided experiment.

07Examples

ex-038-01Reading nested paths Browser-executable JavaScript

Each . or [ ] moves one level deeper.

const school = {
  name: "Hillside",
  classes: [
    { room: "A1", students: ["Ada", "Bo"] },
    { room: "B2", students: ["Cy"] }
  ]
};
console.log(school.classes[0].room);
console.log(school.classes[0].students[1]);
console.log(school.classes.length, school.classes[1].students.length);
Sample input
None
Expected output
A1 Bo 2 1
Common mistake
Forgetting the index: school.classes.room is undefined.
Try this
Print the only student in B2.
Source
examples/ex-038-01-read-paths.js (repository pending publication)

ex-038-02Updating nested values Browser-executable JavaScript

Assign at the end of a path.

const profile = { name: "Ada", prefs: { theme: "light", alerts: { email: true } } };
profile.prefs.theme = "dark";
profile.prefs.alerts.sms = false;
console.log(profile.prefs);
Sample input
None
Expected output
{theme: "dark", alerts: {email: true, sms: false}}
Common mistake
Replacing profile.prefs with a new object and losing alerts.
Try this
Turn off email alerts.
Source
examples/ex-038-02-update-nested.js (repository pending publication)

ex-038-03Looping over nested arrays Browser-executable JavaScript

Outer loop over orders, inner loop over items.

const orders = [
  { id: 1, items: [{ price: 4 }, { price: 6 }] },
  { id: 2, items: [{ price: 15 }] }
];
for (const order of orders) {
  let sum = 0;
  for (const item of order.items) sum += item.price;
  console.log(`Order ${order.id}: ${sum}`);
}
Sample input
None
Expected output
Order 1: 10 Order 2: 15
Common mistake
Looping over orders.items, which is undefined.
Try this
Add a grand total of all orders.
Source
examples/ex-038-03-loop-nested.js (repository pending publication)

ex-038-04Nested data as JSON Browser-executable JavaScript

JSON.stringify shows structure; JSON.parse reads it back.

const order = { id: 7, items: [{ sku: "M1", qty: 2 }] };
const text = JSON.stringify(order);
console.log(text);
const back = JSON.parse(text);
console.log(back.items[0].qty);
Sample input
None
Expected output
{"id":7,"items":[{"sku":"M1","qty":2}]} 2
Common mistake
Reading text.items: the JSON string is text, not an object.
Try this
Pretty-print with JSON.stringify(order, null, 2).
Source
examples/ex-038-04-json.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the path

Add the missing index to a nested path.

const store = {
  name: "Corner Shop",
  shelves: [{ label: "Fruit", items: ["Apple", "Pear"] }, { label: "Bread", items: ["Rye"] }]
};
console.log(store.shelves.items[1]);

Shipping label from nested data

Read several nested values.

const order = {
  id: "A-17",
  customer: { first: "Grace", last: "Hopper", address: { street: "1 Navy Way", city: "Arlington", zip: "22201" } },
  items: [{ name: "Notebook" }, { name: "Pen" }]
};
// TODO: print the three-line label

Course report

Summarise nested arrays of objects.

const courses = [
  { title: "JS Basics", lessons: [{ mins: 12, done: true }, { mins: 20, done: true }, { mins: 15, done: false }] },
  { title: "DOM", lessons: [{ mins: 25, done: false }, { mins: 10, done: false }] }
];

09Prediction

Commit to an answer first, then run the real code to compare.

const d = { a: [{ b: { c: [5, 6] } }] };
console.log(d.a[0].b.c[1], d.a.length);

What is printed?

10Debugging investigation

Changing the theme deletes the alert settings

After switching to dark mode, the user's alert preferences are gone.

const settings = { prefs: { theme: "light", alerts: true } };
function setTheme(theme) {
  settings.prefs = { theme };
}
setTheme("dark");
console.log(settings.prefs.theme, settings.prefs.alerts);

More cases in the Debugging Detective Laboratory

11Practical scenario

Reading an API response

A weather API returns nested JSON: a location object and a list of hourly forecasts, each with nested temperature data. The app reads exactly the paths it needs and checks the shape first.

const res = { city: { name: "Oslo" }, hours: [{ t: { c: -2 } }, { t: { c: 0 } }] };
console.log(res.city.name, res.hours[1].t.c);

12Knowledge check

1. What is printed?

const o = { a: { b: 2 } };
console.log(o.a.b);
  • 2
  • b
  • undefined
  • An error

2. What is printed?

const o = { items: [{ n: "Pen" }] };
console.log(o.items[0].n);
  • Pen
  • undefined
  • An error
  • items

3. Why does o.items.n print undefined?

const o = { items: [{ n: "Pen" }] };
console.log(o.items.n);
  • items is an array, so an index is needed
  • n is misspelled
  • Objects cannot be nested
  • console.log is wrong

4. What is the best first step when a deep path throws?

  • Add try/catch everywhere
  • Log each step of the path to find the first undefined
  • Use JSON.stringify
  • Rename the properties

5. What is printed?

console.log(typeof JSON.stringify({ a: [1] }));
  • string
  • object
  • undefined
  • number

6. Many screens read order.customer.address.city. What helps when the data format changes?

  • Copy the path everywhere
  • One accessor function cityOf(order)
  • Global variables
  • Nothing

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Fix the path: Prints Pear; No error
  • Shipping label from nested data: Prints the label; Not hard-coded
  • Course report: Prints the report; courseSummary works alone
  • ex-038-01: output matches the documented expected output
  • ex-038-02: output matches the documented expected output
  • ex-038-03: output matches the documented expected output
  • ex-038-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-08-objects-and-structured-data/lesson-038-nested-objects-and-arrays/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • Real data nests objects and arrays.
  • Follow paths one step at a time with . and [ ].
  • Log each step to find where a path breaks.
  • Use accessor functions for paths used in many places.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation nested objects and arrays
Context: I am learning nested objects and arrays in JavaScript.
Task: Explain how to read paths through nested objects and arrays with an order example.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction nested objects and arrays drill
Context: I have practised nested objects and arrays.
Task: Give me six nested data structures and ask me to write the path to a value.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging nested objects and arrays bug
Context: My code throws Cannot read properties of undefined on a long path.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation nested objects and arrays practice
Context: I finished the nested objects and arrays exercises.
Task: Create three exercises that summarise nested API-style data.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review nested objects and arrays review
Context: Here is my code that uses nested objects and arrays.
Task: Review how my code reads deeply nested data and suggest accessor functions.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.