
Lodash is an incredibly useful utility library that offers a plethora of functions for working with arrays, objects, and more. One of its most powerful features is the get function, which allows you to safely retrieve values from objects without having to worry about whether a property exists at every level of the object hierarchy.
The get function takes three arguments: the object to query, the path of the property you want to access, and an optional default value to return if the property is undefined. That’s particularly helpful when dealing with deeply nested objects where a property might not be defined at every level.
const _ = require('lodash');
const user = {
name: 'Luke Douglas',
address: {
city: 'New York',
zip: '10001'
}
};
// Using Lodash's get function to safely access nested properties
const city = _.get(user, 'address.city', 'Unknown City');
console.log(city); // Output: New York
const country = _.get(user, 'address.country', 'Unknown Country');
console.log(country); // Output: Unknown Country
This eliminates the need for cumbersome checks to ensure each level of the object exists before accessing a property. It streamlines the code and reduces the chance of running into errors.
In addition to basic property retrieval, the get function also supports arrays within the object. If you have an array of objects, you can use the same approach to navigate through the array elements and their properties.
const users = [
{ id: 1, name: 'Alice', hobbies: ['reading', 'hiking'] },
{ id: 2, name: 'Bob', hobbies: ['gaming'] }
];
// Accessing nested properties in an array of objects
const hobby = _.get(users, '[0].hobbies[1]', 'No hobbies found');
console.log(hobby); // Output: hiking
The beauty of using get is that it always returns a consistent value, whether it is the actual value from the object or the default you specify. This makes it much easier to handle cases where data might be absent, which is common in real-world applications.
Another key aspect to consider is that get can handle dynamic paths by using variables or expressions to specify the path. This can be quite handy in scenarios where the path is not known ahead of time or is subject to change.
const path = 'address.zip'; const zipCode = _.get(user, path, 'No zip code found'); console.log(zipCode); // Output: 10001
By using Lodash’s get, you can write cleaner, more maintainable code that gracefully handles the complexities of data structures. It’s a small change that can lead to a big improvement in your code’s reliability and readability. Understanding how to use this function effectively is a step toward mastering data manipulation in JavaScript, especially when dealing with
ProCase for iPad 9th/ 8th/ 7th Generation Case 10.2 Inch (2021/2020/2019 Release), 10.2 iPad Case 9th/ 8th/ 7th Gen Cover, Slim Smart Cover with Translucent Hard Shell Back -Black
$9.99 (as of June 2, 2026 22:39 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Working with deep nested objects
deeply nested objects that often arise in modern web applications.
When working with APIs or complex data models, you might encounter scenarios where certain properties are optional or vary in their existence. By using get, you can avoid runtime errors that occur when trying to access properties that aren’t defined. That is especially useful in situations where data may come from external sources and is not guaranteed to follow a strict structure.
const apiResponse = {
user: {
id: 123,
profile: {
email: '[email protected]'
}
// 'phone' property might be missing
}
};
// Safe access to potentially missing properties
const phone = _.get(apiResponse, 'user.profile.phone', 'No phone number available');
console.log(phone); // Output: No phone number available
Using the get method in this way not only simplifies your code but also makes it more resilient to changes in the data structure. That’s particularly beneficial when working with data that may evolve over time, such as when new features are added to an API.
Moreover, Lodash’s get function can also be used in conjunction with other Lodash methods to perform more complex operations. For instance, you might want to filter an array of objects based on a nested property and then retrieve a specific value.
const products = [
{ id: 1, details: { price: 100, available: true } },
{ id: 2, details: { price: 150, available: false } }
];
// Filtering products based on availability
const availableProducts = products.filter(product => _.get(product, 'details.available', false));
console.log(availableProducts); // Output: [{ id: 1, details: { price: 100, available: true }}]
This demonstrates how the get function can be integrated into more complex logic, allowing for concise and readable code that still adheres to safety principles when accessing nested properties.
When you embrace Lodash’s get, you’re not just making your code cleaner; you’re also enhancing its robustness against the inevitable changes and inconsistencies that come with real-world data. Understanding its capabilities will empower you to tackle more challenging data manipulation tasks with confidence.
