JSON
Data Processing
Nested Objects
Programming
Accessing Arrays

How can I access and process nested objects, arrays, or JSON?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Nested data appears in API responses, configuration files, and document databases, so sooner or later every developer has to work with it. The important part is not just reaching a deep value, but doing it safely, iterating correctly, and reshaping the result into something the rest of the program can use.

Access Nested Values Deliberately

Once JSON is parsed in JavaScript, it becomes ordinary objects and arrays. Objects are accessed by key, and arrays are accessed by index.

javascript
1const payload = {
2  user: {
3    id: 7,
4    profile: {
5      name: "Mina",
6      emails: ["[email protected]", "[email protected]"]
7    }
8  }
9};
10
11console.log(payload.user.profile.name);
12console.log(payload.user.profile.emails[0]);

That direct style is fine when the structure is guaranteed. It becomes risky when fields may be absent or null.

Use Safe Access for Optional Paths

Optional chaining keeps code from failing when an intermediate property is missing.

javascript
1const payload = {
2  user: {
3    profile: null
4  }
5};
6
7const name = payload.user?.profile?.name;
8const displayName = name ?? "Anonymous";
9
10console.log(displayName);

This is much cleaner than writing several nested guards. It also communicates intent clearly: the path is expected to be optional.

Handle Arrays and Objects With the Right Tools

Nested structures usually mix repeated lists with named fields, so use array helpers for arrays and object helpers for objects.

javascript
1const order = {
2  id: 1001,
3  items: [
4    { name: "Keyboard", price: 50 },
5    { name: "Mouse", price: 25 }
6  ],
7  shipping: {
8    city: "Toronto",
9    country: "Canada"
10  }
11};
12
13const itemNames = order.items.map(item => item.name);
14console.log(itemNames);
15
16for (const [key, value] of Object.entries(order.shipping)) {
17  console.log(key, value);
18}

Trying to treat everything as a generic loop usually makes the code harder to follow. A small amount of structure-aware code is easier to maintain.

Transform Deep Data Early

A useful pattern is to convert raw nested payloads into a simpler shape as soon as they enter your application. That prevents the same deep path from being repeated all over the codebase.

javascript
1const response = {
2  data: {
3    customers: [
4      { id: 1, profile: { name: "Ava" }, active: true },
5      { id: 2, profile: { name: "Leo" }, active: false }
6    ]
7  }
8};
9
10const activeNames = response.data.customers
11  .filter(customer => customer.active)
12  .map(customer => customer.profile.name);
13
14console.log(activeNames);

This kind of small transformation is often the real goal of "processing JSON." The application rarely needs the entire raw payload forever.

Use Recursion Only for Unknown Depth

If the nesting depth is variable, recursion can walk the structure cleanly.

javascript
1function collectStrings(value, result = []) {
2  if (Array.isArray(value)) {
3    for (const item of value) {
4      collectStrings(item, result);
5    }
6  } else if (value && typeof value === "object") {
7    for (const nested of Object.values(value)) {
8      collectStrings(nested, result);
9    }
10  } else if (typeof value === "string") {
11    result.push(value);
12  }
13
14  return result;
15}
16
17const sample = {
18  name: "Ava",
19  tags: ["admin", "team-a"],
20  details: { city: "Paris" }
21};
22
23console.log(collectStrings(sample));

Recursion is useful when the shape is not fixed. If the structure is known in advance, straightforward property access is usually clearer.

Parse JSON Strings Before Using Them

Sometimes the input is still a JSON string rather than an object. In that case, parse first.

javascript
1const raw = '{"status":"ok","count":3}';
2const parsed = JSON.parse(raw);
3
4console.log(parsed.status);

This sounds basic, but many bugs come from forgetting whether a value is raw text or already parsed data.

Common Pitfalls

  • Assuming every nested key exists and then getting an undefined access error.
  • Forgetting whether the current value is an array or an object.
  • Repeating deep property paths in many places instead of transforming once near the boundary.
  • Treating a JSON string as if it were already parsed.
  • Using recursion for simple fixed structures where direct access would be easier to read.

Summary

  • Access objects by key and arrays by index.
  • Use optional chaining and default values when paths may be missing.
  • Process arrays and objects with the iteration tools that fit each type.
  • Reshape nested payloads early so the rest of the code stays simple.
  • Reserve recursion for cases where the nesting depth is unknown or variable.

Course illustration
Course illustration

All Rights Reserved.