- It reduces the lines of code significantly
- Supports common operations done on Objects and Arrays
- Supports common operations on strings
- Supports generic functions
- Trusted by other developers. It has 50k+ ⭐️ on GitHub
- Well Documented
npm install lodash
When dealing with API responses, more often than not, the data you'd like to access will be deeply nested.
Consider the following example.
This is a sample response from the JSON API
If we want to access the title, we could do something like this
This works fine but we made a big assumption:
'deepObject' , 'data' , 'attributes' ,'title' are all defined.
However, it is possible that any of them might be undefined. This would throw an error. If 'attributes' is empty or undefined, then 'attributes.title' would not exist.
Lodash's get function can be used to handle the error gracefully. Below is the syntax
_.get(object, path, [defaultValue])
In the second console statement, we try to access the element at index 3 in data but this doesn't exist. Therefore 'Value doesn't exist' is printed in the console.
In the third console statement, we try to print the value for 'title' in 'data' but 'data' doesn't have any attribute called 'title'. Similar to the above case, 'Value doesn't exist' is printed in the console.
We will work with the same object we were working with earlier.
If we want to add a new key-value pair for subtitle inside 'attributes', we could do something like this
Again, we made a similar assumption that the entire path is defined. However, if any part of the path is undefined, it will throw an error.
We can use Lodash's set function to handle this error gracefully. Below is the syntax
_.set(object, path, value)
If the path doesn't exist, it will create the path.
set is an in-place function, i.e it updates the input object. Our new object is below
The second set operation added 3 elements (2 empty elements) to the 'data' array while the third set operation added an attribute 'subtitle' to 'data'
We can use the has function to check if a path exists in an object. Below is the syntax
Lodash's invert function will invert the keys and values. Below is the syntax
If you have a object and want to create an object with some of the keys from the original object, you can use Lodash's pick function. It doesn't add the key and value directly, if the path provided is nested, it will recreate the path as well. If you are confused, refer to the example below
Below is the syntax
Let's work with the JSON API response again.
Instead of directly adding title directly, it recreate the path 'data.attributes.title'.
As you can see, the original object remains unchanged.
Lodash has a bunch of other useful functions, refer to their documentation for more