Learn Lodash: Make your JS code more elegant and readable
-
- I. Introduction:
- 2. Getting Started with Lodash
- 3. Commonly used APIs in Lodash
-
- 1. Array related API
-
- _.chunk(array, [size=1])
- _.compact(array)
- _.concat(array, [values])
- _.drop(array, [n=1])
- _.dropRight(array, [n=1])
- _.fill(array, value, [start=0], [end=array.length])
- _.pull(array, [values])
- _.pullAll(array, [values])
- _.pullAt(array, [indexes])
- _.indexOf(array, value, [fromIndex=0])
- _.lastIndexOf(array, value, [fromIndex=array.length-1])
- _.reverse(array)
- 2. Object related API
- 3. String related API
- 4. Summary
I. Introduction:
As JavaScript
the language continues to evolve, more and more developers rely on its powerful features and adaptability to build modern web applications and websites. However, as the code base becomes larger and more complex, we may encounter some problems dealing with different data structures. At this time, we can use Lodash
toolkits to make our JS code more elegant and easier to read.
Lodash
It is a very popular JavaScript
utility library that provides many useful function methods to simplify our daily tasks. Lodash provides many efficient and practical functions, such as lodash.map
, lodash.filter
, lodash.groupBy
etc., which allow us to simply operate on common data types such as arrays, objects, and strings.
If you haven’t used Lodash yet, this article will introduce you to Lodash
some core concepts and show you how to use Lodash to write clear and concise JS code.
2. Getting Started with Lodash
Lodash can be easily npm
imported and used. If you haven't installed Lodash yet, you can complete the installation by entering the following command in the console:
npm install --save lodash
import
Once installed, you can import Lodash by using the ES6 " " statement in your JavaScript file :
import _ from 'lodash';
Of course, you can also choose to script
include Lodash directly in the " " tag of the HTML file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
Now that we know how to do it , let's take a deeper look Lodash
at some examples .Lodash
3. Commonly used APIs in Lodash
Because the official documentation of lodash provides many methods for operating data structures, but not every method is very practical. Some methods have few application scenarios and are useless. It is impossible for me to explain every method in this article. , so I will focus on selecting the most practical and widely used methods to introduce the Lodash
commonly used ones API
.
1. Array related API
In Lodash, arrays are one of the most commonly used data types. The following are commonly used APIs:
_.chunk(array, [size=1])
This function divides an array into multiple array blocks according to the specified size and returns a new array composed of these blocks .
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let chunks = _.chunk(array, 3);
console.log(chunks);
// 输出结果:
// [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
_.compact(array)
This function is used to remove all false value elements from the array and return a new array ( false
, null
, 0
, ""
, undefined
and NaN
) with false values filtered out .
let array = ['foo', false, 0, undefined, NaN, '', 246];
let compacted = _.compact(array);
console.log(compacted);
// 输出结果:
// [ "foo", 246 ]
_.concat(array, [values])
This function is used to create a new array, concatenate it with any array or value, and return the new arrayarray
after concatenation . This is similar to the native JS concat method. Here is a brief explanation:
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
let array3 = [7, 8, 9];
let concatenated = _.concat(array1, array2, array3);
console.log(concatenated);
// 输出结果:
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
_.drop(array, [n=1])
This function removes the previousarray
element and returns a new array consisting of the remaining elements .n
let array = [1, 2, 3, 4, 5, 6];
let dropped = _.drop(array, 3);
console.log(dropped);
// 输出结果:
// [4, 5, 6]
_.dropRight(array, [n=1])
This function is used to remove the lastn
element of an array and return the remaining elements 新数组
.
let array = [1, 2, 3, 4, 5, 6];
let dropped = _.dropRight(array, 2);
console.log(dropped);
// 输出结果:
// [1, 2, 3, 4]
_.fill(array, value, [start=0], [end=array.length])
This function is used value
to fill (replace) with values array
, start
starting from the position and end
ending at the position (but not including the end position).
let array = [1, 2, 3, 4, 5];
_.fill(array, 'a', 1, 3);
console.log(array);
// 输出结果:
// [1, 'a', 'a', 4, 5]
_.pull(array, [values])
This function is used to remove all elements in the array that are equal to the given value:
let array = [1, 2, 3, 1, 2, 3];
const result = _.pull(array, 2, 3);
console.log(result);
// 输出结果:
// [1, 1]
_.pullAll(array, [values])
This method is similar _.pull
, except that this method accepts an array of values to remove.
var array = [1, 2, 3, 1, 2, 3];
const result = _.pullAll(array, [2, 3]);
console.log(result); // 控制台打印结果:[1, 1]
_.pullAt(array, [indexes])
This function is used to indexes
remove the corresponding element in the array based on the index and return the array of the removed element.
var array = [5, 10, 15, 20];
var evens = _.pullAt(array, 1, 3);
console.log(array);
// => [5, 15]
console.log(evens);
// => [10, 20]
_.indexOf(array, value, [fromIndex=0])
This function is used to find the position of a specified value in an array starting from the head .
let array = [1, 2, 3, 4, 5];
console.log(_.indexOf(array, 3));
// 输出结果:
// 2
_.lastIndexOf(array, value, [fromIndex=array.length-1])
This function is used to find the position of a specified value in an array starting from the end .
let array = [1, 2, 3, 4, 5, 3];
console.log(_.lastIndexOf(array, 3));
// 输出结果:
// 5
_.reverse(array)
This function is used to sort the elements in an array in reverse order and return the array in reverse order.
let array = [1, 2, 3, 4, 5];
let reversed = _.reverse(array);
console.log(reversed);
// 输出结果:
// [5, 4, 3, 2, 1]
2. Object related API
In Lodash, objects are also one of the commonly used data types. The following are commonly used APIs:
_.assign(object, [sources])
This function is used to assign enumerable properties of the source object to the target object. The application rules for source objects are from left to right, and the properties of the next object will overwrite the properties of the previous object.
NOTE: This method is subject to change
object
, refer toObject.assign
.
let object = {
name: 'John',
age: 25,
score: 80,
};
let source1 = {
name: 'Jane' };
let source2 = {
age: 28 };
_.assign(object, source1, source2);
console.log(object);
// 输出结果:
// {
// name: 'Jane',
// age: 28,
// score: 80
// }
_.omit(object, [props])
Reverse version _.pick
; This method takes an object, which consists of the object itself and inherited enumerable properties except for ignored properties.
(Note: It can be understood as deleting the attributes of the object object ).
let object = {
name: 'John',
age: 25,
score: 80,
};
let withoutScore = _.omit(object, 'score');
console.log(withoutScore);
// 输出结果:
// {
// name: 'John',
// age: 25,
// }
_.pick(object, [props])
This function is used to create a shallow copy of an object and retain only the properties of the specified key.
let object = {
name: 'John',
age: 25,
score: 80,
};
let picked = _.pick(object, ['name', 'age']);
console.log(picked);
// 输出结果:
// {
// name: 'John',
// age: 25,
// }
_.isEqual(value, other)
This function is used to compare whether two values are equal, and supports comparison 对象
, 数组
, 正则表达式
etc.
Note: This method supports comparisons of
arrays
,array buffers
,booleans
,date objects
,error objects
,maps
,numbers
,Object objects
,regexes
,sets
,strings
,symbols
, andtyped arrays
the
Object
object's own properties, excluding inherited and enumerable properties. Function and node comparisons are not supported .DOM
console.log(_.isEqual('abc', 'abc')); // true
console.log(_.isEqual({
a: 1}, {
a: 1})); // true
console.log(_.isEqual([1, 2], [1, 2])); // true
console.log(_.isEqual(/abc/g, /abc/g)); // true
_.merge(object, [sources])
This function is used to merge two or more objects into a new object.
This method is similar _.assign
, except that it recursively merges sources
the source object itself and inherited enumerable properties into object
the target object. If the target value exists, the source object properties being parsed to undefined
will sources
be skipped. Arrays and ordinary objects are merged recursively, and other objects and values are overwritten by direct allocation. Source objects are allocated from left to right . Subsequent source object properties overwrite previously assigned properties.
let object1 = {
'a': 1 };
let object2 = {
'b': 2 };
let merged = _.merge(object1, object2);
console.log(merged);
// 输出结果:
// { 'a': 1, 'b': 2 }
.omitBy(object, [predicate=.identity])
This function is used to create a shallow copy of an object, but filter out the properties that meet the specified conditions.
Reverse version _.pickBy
; this method is an object. This object ignores predicate
(assert function) the attributes that are not true values and object
consists of itself and inherited enumerable attributes. predicate
Called with 2 parameters: ( value
, key
).
let object = {
name: 'John',
age: 25,
score: 80,
};
let filtered = _.omitBy(object, function(value, key) {
return key === 'score';
});
console.log(filtered);
// 输出结果:
// {
// name: 'John',
// age: 25,
// }
.pickBy(object, [predicate=.identity])
This function is used to create an object consisting of properties whose values are determined to be true object
from . Called with 2 parameters: ( , ).predicate
predicate
value
key
let object = {
name: 'John',
age: 25,
score: 80,
};
let picked = _.pickBy(object, function(value, key) {
return key !== 'score';
});
console.log(picked);
// 输出结果:
// {
// name: 'John',
// age: 25,
// }
3. String related API
In Lodash, strings are also one of the commonly used data types. The following are commonly used APIs:
_.kebabCase
This function is used to convert a string into kebab case (hyphen connected words) format.
console.log(_.kebabCase('foo_bar_baz')); // 'foo-bar-baz'
_.camelCase
This function is used to convert a string into camel case format.
console.log(_.camelCase('foo-bar-baz')); // 'fooBarBaz'
_.snakeCase
This function is used to convert a string into snake case (underscore connected words) format.
console.log(_.snakeCase('fooBarBaz')); // 'foo_bar_baz'
_.startsWith
This function is used to determine whether a string starts with a specified character.
console.log(_.startsWith('lodash', 'lod')); // true
_.endsWith
This function is used to determine whether the string ends with the specified character.
console.log(_.endsWith('lodash', 'sh')); // true
_.repeat
This function is used to repeat a string n times.
let repeated = _.repeat('abc', 3);
console.log(repeated);
// 输出结果:
// 'abcabcabc'
The above are some commonly used APIs in Lodash. These APIs can help us process data more conveniently and efficiently.
4. Summary
Lodash
It is an essential JavaScript
tool library that can help us process data concisely and easily. Lodash provides many powerful functions, mainly used to operate data types such as arrays, objects, and strings. It also provides many practical functions, such as, , and merge
so debounce
on throttle
. The use of Lodash allows us to write JavaScript code faster and more efficiently. I hope this article can help you learn Lodash
and apply it in actual development.