How I started to use Lodash in the Front end (React JS)
Today I want to share how I use Lodash JS library in my Front end code. After I start to use the Loadsh library, I found many advantages to using it. In this post, I want to introduce the below 4 things.
- What is Lodash
- Why you should use Lodash
- How to install
- How I use Lodash
What is Lodash
Lodash is “A modern JavaScript utility library delivering modularity, performance & extras” (from Loadsh.com) Lodash can cover common manipulation programming for arrays, objects, string, and collections using functional programming paradigm.
Why you should use Lodash
I found Lodash is very useful when I handle nested array or objects. By using functions supported by Lodash, you can chain the Lodash functions so you can perform complicated array or objects manipulations easily. This can lead your code to have more modularity with less code when you need to deal with a complex data structure.
How to install
If you want to use Lodash with frameworks (React, Vue, Angular, NodeJs), you can install Lodash via npm by running the following command:
npm install — save lodash
You can use Loadash by simply importing functions that you want to use:
import { get, isEmpty, find, filter, has, debounce } from ‘loadash’;
How I use Lodash
Test if an object or an array is empty or not
isEmpty(obj);
isEmpty() accepts only one parameter, an object or an array, and returns true if ‘obj’ is empty and false if not.
Test if an array has an item that satisfies a custom condition
find(testArray, function(item number) {
Return item > 0;
}, 0);
find() accepts three parameters, 1. an array to find, 2. a function to be called until a condition meets, 3. index of the array to start a search. It returns one matching item from the array.
Test if an array has multiple items that satisfies a custom condition
filter(testArray, function(item number) {
return number > 0;
}
filter() accepts two parameters, 1. an array to find,
Test Get
const testObj = {‘a’: ‘b’: ‘val’};
get(testObj, a.b, ‘default_val’)
Get() accepts three parameters, 1. object to get, 2. path to get, 3. default value if nothing found. I found this function useful to define the default value if nothing found from a nested object or array in this simple 1 line code.