Get value for key from nested JSON object in JavaScript

In JavaScript, accessing values from nested JSON objects is a common task when working with APIs and complex data structures. We can retrieve nested values using dot notation, bracket notation, or custom functions.

Before exploring different approaches, let's understand what JSON and nested JSON objects are:

What is JSON and Nested JSON Objects?

JSON (JavaScript Object Notation) is a lightweight, text-based format for representing structured data. It's widely used for data transmission between web applications and servers.

Nested JSON objects contain objects within other objects, creating a hierarchical structure. Each nested property has a unique path that can be accessed using different methods.

{
  "name": "Super Hero Team",
  "homeTown": "Metro City",
  "birthYear": 2000,
  "active": true,
  "members": [
    {
      "name": "Molecule Man",
      "age": 29,
      "powers": ["Radiation resistance", "Turning tiny", "Radiation blast"]
    },
    {
      "name": "Madame Uppercut", 
      "age": 39,
      "powers": ["Million tonne punch", "Damage resistance"]
    }
  ]
}

Method 1: Using Dot Notation and Bracket Notation

The most straightforward approach is to use dot notation (object.property) or bracket notation (object["property"]) to access nested values directly.

// Example JSON object
const data = {
  "name": "John",
  "age": 30,
  "address": {
    "street": "123 Main St",
    "city": "Anytown",
    "state": "CA"
  }
};

// Accessing nested properties with dot notation
const name = data.name;
const street = data.address.street;
console.log("Name: " + name + ", Street: " + street);

// Accessing nested properties with bracket notation
const age = data["age"];
const state = data["address"]["state"];
console.log("Age: " + age + ", State: " + state);
Name: John, Street: 123 Main St
Age: 30, State: CA

Method 2: Using a Dynamic Access Function

For more complex scenarios, we can create a function that accepts a string path and dynamically traverses the object structure.

// Example JSON object
const data = {
  "name": "John",
  "age": 30,
  "address": {
    "street": "421 Main Street",
    "city": "Anytown", 
    "state": "CA"
  }
};

// Function to access nested properties using string paths
function getNestedValue(obj, path) {
  // Handle direct property access
  if (path in obj) {
    return obj[path];
  }
  
  // Split path by dots and traverse
  const keys = path.split(".");
  let value = obj;
  
  for (let i = 0; i < keys.length; i++) {
    value = value[keys[i]];
    if (value === undefined) {
      break;
    }
  }
  
  return value;
}

// Using the function to access nested values
const name = getNestedValue(data, "name");
const age = getNestedValue(data, "age");
const street = getNestedValue(data, "address.street");
const state = getNestedValue(data, "address.state");

console.log("Name:", name);
console.log("Age:", age);
console.log("Street:", street);
console.log("State:", state);
Name: John
Age: 30
Street: 421 Main Street
State: CA

Method 3: Safe Access with Optional Chaining

Modern JavaScript supports optional chaining (?.) to safely access nested properties without throwing errors if intermediate properties are undefined.

const data = {
  "user": {
    "profile": {
      "name": "Alice",
      "contact": {
        "email": "alice@example.com"
      }
    }
  }
};

// Safe access using optional chaining
console.log("Name:", data.user?.profile?.name);
console.log("Email:", data.user?.profile?.contact?.email);
console.log("Phone:", data.user?.profile?.contact?.phone || "Not available");
Name: Alice
Email: alice@example.com
Phone: Not available

Comparison of Methods

Method Time Complexity Error Handling Dynamic Paths
Dot/Bracket Notation O(1) Throws errors No
Custom Function O(n) Returns undefined Yes
Optional Chaining O(1) Safe (returns undefined) No

Conclusion

Choose dot notation for simple, known structures, optional chaining for safe access, and custom functions when you need dynamic path traversal. Each method serves different use cases in handling nested JSON data effectively.

Updated on: 2026-03-15T23:19:00+05:30

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements