01 / 21
{ {} }

Working with
Nested JSON

Learn to navigate, access, and manipulate deeply nested objects and arrays in JavaScript using dot notation, bracket notation, and powerful iteration patterns.

JavaScript

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data format used to store and exchange structured information. It closely mirrors JavaScript object syntax, making it the lingua franca of web APIs and configuration files.

Objects
Key-value pairs wrapped in curly braces: { }
Arrays
Ordered lists wrapped in square brackets: [ ]
Values
Strings, numbers, booleans, null, objects, or arrays

What Makes JSON Nested?

Nesting means placing objects inside objects, arrays inside arrays, or any combination. Each value can itself be a complex structure, creating a tree of data with multiple levels of depth.

user (object) "name": "Ada" "age": 28 address (object) "city": "London" coords (object) "lat": 51.5 "lng": -0.1 Depth 0 Depth 1 Depth 2 Depth 3

Why Nested JSON Matters

Almost every modern web application consumes data from APIs that return nested JSON. Understanding how to traverse, extract, and transform this data is a foundational developer skill.

1
APIs return complex structures: a single weather response may nest location, forecast arrays, and alert objects.
2
Config files use nesting: package.json, tsconfig, and .eslintrc all rely on nested objects.
3
Databases mirror nested models: NoSQL stores like MongoDB use deeply nested documents.

The Two Access Notations

JavaScript gives you two ways to dig into nested structures: dot notation and bracket notation. Both can be chained to reach any depth.

Dot Notation
Clean, readable, but keys must be valid identifiers (no spaces, no starting with digits).
Bracket Notation
Handles any key string and dynamic variables: obj["my key"] or obj[varName].
// Dot notation const city = user.address.city; // Bracket notation const city = user["address"]["city"]; // Mixed (array inside object) const first = user.hobbies[0];

Core Rule: Chaining Access

To reach a value at depth \( n \), chain exactly \( n \) access operations. Each step resolves one level of nesting before the next step runs.

data root object . .results array → [0] 1st element . .score number = 95 data.results[0].score → 95

Dot vs Bracket: When to Use Which

Dot Notation Bracket Notation
Syntax obj.key obj["key"]
Dynamic Keys ✕ No ✓ Yes
Special Characters ✕ No ✓ Yes
Numeric Keys ✕ No ✓ Yes
Readability ✓ High Moderate
Best For Static, known keys Variables, loops, odd keys

How to Navigate Nested JSON

1
Identify the target value: what specific piece of data do you need?
2
Trace the path from root: list every key and index from the top-level object down to the target.
3
Chain accessors: write dot or bracket for each level.
4
Guard against undefined: use optional chaining (?.) or check each level before accessing the next.
5
Test in console: log intermediate values to verify you're on the right path.

Example 1: Basic Nesting

const student = { name: "Kai", grades: { math: 92, english: 88 } }; // Access Kai's math grade console.log(student.grades.math); // 92

Example 2: Arrays Inside Objects

const library = { name: "City Library", books: [ { title: "Dune", year: 1965 }, { title: "Neuromancer", year: 1984 } ] }; // Get the title of the second book console.log(library.books[1].title); // "Neuromancer"

Example 3: Deep API Data

const api = { status: "ok", data: { users: [ { id: 1, profile: { avatar: "pic.jpg", bio: "Hello!" } } ] } }; // Get the first user's bio (4 levels deep) api.data.users[0].profile.bio; // "Hello!"

Iterating Nested Arrays

When an object contains an array, use .forEach(), .map(), or for...of to process each element. Combine iteration with property access to extract what you need.

const school = { classes: [ { name: "Algebra", students: 30 }, { name: "Biology", students: 25 } ] }; // Extract all class names const names = school.classes.map(c => c.name); // ["Algebra", "Biology"]

Safe Access with Optional Chaining

If any intermediate level is undefined or null, the chain throws a TypeError. The ?. operator short-circuits and returns undefined instead of crashing.

// Without optional chaining: CRASH if profile is missing user.profile.avatar; // TypeError! // With optional chaining: safe user?.profile?.avatar; // undefined // Combine with nullish coalescing for defaults user?.profile?.avatar ?? "default.png";

Destructuring Nested Structures

Destructuring lets you unpack values from nested objects and arrays into named variables in a single statement, reducing repetitive access chains.

const response = { data: { user: { name: "Zara", role: "admin" } } }; // Nested destructuring const { data: { user: { name, role } } } = response; console.log(name); // "Zara" console.log(role); // "admin"

Common Mistakes

✕ Off-by-One Index
Using [1] to get the first element instead of [0]. Arrays are zero-indexed.
✕ Missing Level
Skipping an intermediate key: api.users.bio instead of api.data.users[0].bio.
✕ No Null Check
Accessing a property on undefined without ?. causes a runtime crash.
✕ String vs Object
Forgetting to JSON.parse() a JSON string before accessing properties.

Technique Comparison

Technique Best For Handles Missing?
Dot Notation Static, known keys ✕ No
Bracket Notation Dynamic keys, loops ✕ No
Optional Chaining Uncertain data shapes ✓ Yes
Destructuring Extracting multiple values Partial (with defaults)
.map() / .forEach() Processing nested arrays ✕ No

Question 1 of 5

Which expression correctly returns "Phone"?

Question 2 of 5

What does user?.address?.zip return if user.address is undefined?

Question 3 of 5

Which expression returns "Python"?

Question 4 of 5

Given const obj = { a: { b: { c: 42 } } };, which destructuring correctly extracts c?

Question 5 of 5

What does config.cache?.ttl ?? 300 evaluate to?