Use Lodash to Simplify Your Javascript Code

Recall the following code? You need to retrieve a property value deep in an object. It smells, doesn’t it?
How can we write it better?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const extractFirstErrorDetails = (errorResponse) => {
if (errorResponse) {
const data = errorResponse.data;
if(data) {

if(data.errors) {
if(data.errors[0]) {
const errorDetails = data.errors[0].detail;
if(errorDetails) {
return errorDetails;
}
}

}
}
}
return "";
};

using lodash

_.get(errorResponse, 'data.errors[0].detail', '')

this is the lodash get method

_.get(object, path, [defaultValue])

Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.