Working with deeply nested objects in JavaScript can be very complex sometimes, especially when you need to access nested object properties in JavaScript dynamically. Manually navigating and accessing each nested object can be more complex and time-consuming. So, you can simplify this by using a nested property path, which is a string that allows you to easily access nested object properties by string path in JavaScript. This method streamlines the JavaScript object path lookup process and makes your code cleaner and more efficient.
In this article, we will learn how to access a nested object property using a path string in JavaScript and optimize the approach using modern JavaScript features like reduce(), optional chaining, and external utility libraries.
Table of Contents:
What Is a Nested Object Property?
A nested object in JavaScript is an object that contains another object inside it, and that object contains another, and so on. In other words, nested objects in JavaScript are object that contains another object inside them. So, a “nested object property” is the property of nested objects.
Example:
const data = {
Learner: {
profile: {
name: "Kuldeep"
}
}
};
Now, to access the name, you have to use the JavaScript nested property path “user.profile.name“
Problem with Accessing Nested Object Properties Using Path Strings
The problem is that you have to access a nested object property using a path string in JavaScript. Let’s say you have an object representing the details of a learner from Intellipaat.
const learner = {
name: "Intellipaat Learner",
address: {
city: "Bangalore",
zip: {
code: "12341",
extended: "1234"
}
}
}
Now, what if you want to access the learner.address.zip.code property dynamically, using a string path like address.zip.code. Accessing it directly by using learner[“address.zip.code”] didn’t work because JavaScript doesn’t understand dot notation on strings automatically. Thus, we need a function that can take both the object and the path string and return the correct value.
Methods To Access Nested Object Properties
Here are two methods to access nested object properties efficiently from the object in JavaScript. Let’s discuss each one by one:
Method 1: Using split() and reduce() Methods
One simple way to get the nested object property is by using the split() and reduce() methods together. The split() method is used to break the path string into parts using dots (.) and reduce() to traverse the object.
Example:
Output:
Explanation: In this example, you are using the split() and reduce() methods to access the nested property of the object. If the path string is valid, then it will give you the value; otherwise, it will give you undefined.
Method 2: Using Optional Chaining
Optional chaining (?.) in JavaScript provides a smarter way to access deeply nested properties safely. This modern method helps you to read properties that might not exist without causing a TypeError. Also, if any part of the chain is null or undefined, the entire expression evaluates to undefined, thus preventing your application from crashing.
Example:
Output:
Explanation: In this example, optional chaining is used to get the properties of the nested object. Optional chaining helps you write less code and produce better results.
Method 3: Using External Utility Libraries
Using an external utility library is another great option to access nested object properties in JavaScript. You can use the Lodash library for doing this because it offers various built-in functions to access nested object properties in JavaScript
Output:
Output:
In this example, Lodash’s get() function is used to safely access a nested value inside the learner object. Here, lodash.get(learner, “address.zip.code”) retrieves the value “12341”. It didn’t throw an error even if the path doesn’t exist; besides throwing an error, it returns undefined.
Reduce vs Optional chaining vs Lodash
Feature |
reduce() |
Optional Chaining |
Lodash |
Purpose |
Aggregates an array into a single value. |
Safely accesses nested properties or methods. |
Utility belt for common JS tasks (data, functions, etc.). |
Use Case |
Summing, grouping, and flattening arrays. |
Safely reading deep object paths. |
Deep cloning, debouncing, and advanced array or object manipulation. |
Error |
Requires manual checks (e.g., for empty arrays). |
Prevents TypeError for null or undefined references. |
Offers safe methods like _.get(). |
Perf. |
Good, native method. |
Very fast; native language feature. |
Good, optimized, but adds minor library overhead. |
Syntax |
areduce((acc, val) => {}, initialVal) |
obj?.prop?.nestedProp |
_.get(obj, ‘prop.nestedProp’) |
Support |
ES5+ (universal). |
ES2020+ (modern browsers). |
Requires library import (works everywhere). |
Real-World Use Cases of Accessing Nested Object Properties
Here are some of the real-world use cases that show why accessing nested object properties in JavaScript is important:
- It is used in data manipulation in analytics or dashboards.
- To work with APIs that return complex JSON.
- Used for handling form data in React/Angular/Vue apps.
- It is used for logging or extracting user data in applications.
Conclusion
In this article, we have discussed that nested objects in JavaScript are objects that contain another object inside them. By using JavaScript’s reduce method, optional chaining, and external utility libraries, you can efficiently get nested object properties using a path string. Our final function provides a robust solution for dynamic object traversal. Also, the real-world use cases of accessing nested object properties in JavaScript will help you to use this function in your real-life projects and applications.
Get Nested Object Property By Path String in JavaScript – FAQs
Q1. How to access a property of the nested object in JavaScript?
You can get nested objects properties in JavaScript using the dot (.) notation or bracket notation ( [ ] ).
Q2. How to iterate over a nested object in JavaScript?
You can iterate nested objects in JavaScript using recursion, or another popular way to iterate over nested objects is the for…in loop.
Q3. How to get the values of an object in JavaScript?
For getting the values of an object in JavaScript, Object.values() is used: Syntax: console.log(Object.values(obj));
Q4. What is an optional chain expression?
Optional chaining (?.) in JavaScript is used to safely access deeply nested properties without any errors.
Q5. How to convert a JavaScript object to a string?
To convert an object in JavaScript into a string, you can use JSON.stringify() method. Syntax: console.log(JSON.stringify(obj));