Lodash stands out as a widely-used JavaScript library that offers over 200 functions to streamline web development processes. From map and filter to function binding, template creation, deep equality checks, and index generation, Lodash caters to various needs in web development. Moreover, it seamlessly integrates with both browsers and Node.js environments.
Manipulating objects in JavaScript can be intricate, especially when dealing with extensive modifications. With its array of features, Lodash simplifies object manipulation tasks effectively.
Being an open-source project, Lodash allows easy contribution from users. You can extend the library by adding plugins and sharing them on GitHub or through Node.js.
Syntax
_.get(object, path, [defaultValue]) retrieves the value at the specified path within an object. In case the resolved value is undefined, the defaultValue takes its place.
Arguments
object (Object) − The object to be queried.
path (Array|string) − The property's path to retrieve.
[defaultValue] (*) − The value to return for unresolved values.
If you have integrated lodash into your project, utilize the following:
_.get(resp,"userdetails.name")
as mentioned in the documentation.
If you haven't yet added lodash, I recommend installing it via npm, as it remains the top choice among utility packages.
Use the command below to install Lodash:
npm install loadash
https://i.sstatic.net/z2tQo.png
Example:
var _ = require("lodash");
var data = [
{ userdetails: { name: "d" } },
{},
{ userdetails: {} },
{ userdetails: { name: "d" } },
];
for (i = 0; i < data.length; i++) {
var resp = data[i];
if (_.get(resp, "userdetails.name") == "d") {
// if (resp.userdetails && resp.userdetails.name == "d") { use without loadlash
console.log("Success");
} else {
console.log("failed");
}
}
Although using lodash may seem complex at first, it effectively prevents runtime errors. The following expressions yield the same outcome:
resp.userdetails && resp.userdetails.name == "d"
===
_.get(resp, "userdetails.name") == "d"