0
0
JavascriptHow-ToBeginner · 3 min read

How to Access Nested JSON in JavaScript Easily

To access nested JSON in JavaScript, use dot notation like obj.key1.key2 or bracket notation like obj['key1']['key2']. This lets you reach values inside objects within objects step-by-step.
📐

Syntax

You can access nested JSON properties using two main ways:

  • Dot notation: Use a dot . to go deeper into the object keys.
  • Bracket notation: Use square brackets [] with the key as a string, useful when keys have spaces or special characters.

Example: object.key1.key2 or object['key1']['key2']

javascript
object.key1.key2;
object['key1']['key2'];
💻

Example

This example shows how to access a nested value inside a JSON object representing a person with address details.

javascript
const person = {
  name: "Alice",
  address: {
    city: "Wonderland",
    zip: "12345",
    coordinates: {
      lat: 51.5074,
      long: 0.1278
    }
  }
};

// Access city using dot notation
const city = person.address.city;

// Access latitude using bracket notation
const latitude = person['address']['coordinates']['lat'];

console.log(city);      // Wonderland
console.log(latitude);  // 51.5074
Output
Wonderland 51.5074
⚠️

Common Pitfalls

Common mistakes when accessing nested JSON include:

  • Trying to access a property of undefined if a key does not exist, causing errors.
  • Mixing dot and bracket notation incorrectly.
  • Not checking if intermediate keys exist before accessing deeper keys.

Use optional chaining ?. to safely access nested properties without errors.

javascript
const data = { user: { profile: null } };

// Wrong: will throw error if profile is null
// const name = data.user.profile.name;

// Right: safely access with optional chaining
const name = data.user.profile?.name;

console.log(name); // undefined
Output
undefined
📊

Quick Reference

NotationUsageWhen to Use
Dot notationobject.key1.key2Simple keys without spaces or special characters
Bracket notationobject['key1']['key2']Keys with spaces, special chars, or dynamic keys
Optional chainingobject?.key1?.key2Safe access when keys might be missing or null

Key Takeaways

Use dot or bracket notation to access nested JSON properties step-by-step.
Bracket notation is useful for keys with spaces or special characters.
Use optional chaining (?.) to avoid errors when keys might be missing.
Always check if intermediate keys exist before accessing deeper levels.
Mixing dot and bracket notation is allowed but be consistent and careful.