The purpose of this article is to list some of the “redundant” apis and their native JS counterparts; Later FOUND too much API, energy is limited, slowly become a record of those help to improve the efficiency of the development of THE API, I hope to help you. I have not done any demos of apis whose actual use is known from their name or description. You can view the corresponding official documentation to quickly apply to the actual development, Lodash Chinese API details.
A, harvest
- Lodash’s powerful apis
- Lodash’s “redundant” API and native JS counterparts
Second, the Lodash
Lodash is a consistent, modular, high-performance JavaScript utility library. Use functional apis, most of which do not modify the parameters passed in;
Lodash is a powerful tool that covers most of the logical function points encountered in front-end development, making it much more efficient to use It. But there’s a downside: convenience tends to make us lazy. At the same time, we should always remember that JavaScript is our foundation;
The “redundant” API in Lodash is not redundant. It handles many exceptions that developers often ignore, making the code more secure.
For most Lodash apis, comparing logic function points to handwritten JS does not improve performance;
Lodash, gitHub star count is 45K. At the same time, it is a learning material to help us strengthen the foundation of JavaScript by reading the source code. Functional apis keep the code per logical function point small and easy to understand. If you are not familiar with JavaScript, you can strengthen JavaScript by reading the source code and writing it by hand, such as handwriting: Currize, buffeting, throttling, bind, string template, etc.
Array Array
“Redundant” index: ☆☆
- Compact (filter false values)
lodash.compact([0.1.false.2.' '.3[])0.1.false.2.' '.3].filter(_= > _)
/ / [1, 2, 3]
Copy the code
- Concat (Array concatenation)
lodash.concat([1], [2.3.4], [5.6[])1. [2.3.4], ...[5.6]]
// [1, 2, 3, 4, 5, 6]
Copy the code
- Fill in
lodash.fill([1.2.3].'a')
[1.2.3].fill('a'))
// ['a', 'a', 'a']
lodash.fill(Array(3),'b')
Array(3).fill('b')
// ['b', 'b', 'b']
Copy the code
- Head (get the first element)
const first1 = lodash.head([1.2.3])
const [first2] = [1.2.3]
/ / 1
Copy the code
- Flatten (down 1 dimension)
lodash.flatten([1[2[3[4]], 5[]]))1[2[3[4]], 5]].flat(1))
// [1, 2, [3, [4]], 5]
Copy the code
- FlattenDeep | flattenDepth (down to a one dimensional array)
lodash.flattenDeep([1[2[3[4]], 5]])
lodash.flattenDepth([1[2[3[4]], 5]], 3)
[1[2[3[4]], 5]].flat(Infinity)
// [1, 2, 3, 4, 5]
Copy the code
- FromPairs (Converting an array of type Entries to objects)
lodash.fromPairs([['fred'.30], ['barney'.40]])
Object.fromEntries([['fred'.30], ['barney'.40]])
// {fred: 30, barney: 40}
Copy the code
- Pull (removes the specified element)
lodash.pull([1.2.3.1.2.3].2.3)
[1.2.3.1.2.3].filter(item= >! [2.3].includes(item))
/ / [1, 1)
Copy the code
- Array of reverse turn (Array), slice (cutting), join (string concatenation), indexOf | lastIndexOf (matching index), etc
“Redundant” index: ☆
- difference
lodash.difference([3.2.1], [4.2[])3.2.1].filter(item= >! [4.2].includes(item))
Copy the code
- Tail (returns an array that does not contain the first element)
var other = lodash.tail([1.2.3])
var [, ...other] = [1.2.3] // Extensibility does not contain the first NTH element
Copy the code
- Take (elements 0-n) is “redundant” if used to delete array elements
let arr1 = [1.2.3.4.5]
arr1 = lodash.take(arr1, 2) // Do the assignment and delete the element
const arr2 = [1.2.3.4.5]
arr2.length = 2 // Change the length, delete the following element directly, can be used to empty array
/ / [1, 2]
Copy the code
The eye-popping API
-
PullAt (select elements by subscript, split into two arrays)
-
TakeRight (returns a slice of an array of n elements starting at the end)
// reverse deconstruction
const [beforeLast, last] = lodash.takeRight([1.2.3.4].2)
console.log(beforeLast, last) / / 3 4
Copy the code
- zipObject
lodash.zipObject(['a'.'b'], [1.2]);
// => { 'a': 1, 'b': 2 }
Copy the code
- zipObjectDeep
lodash.zipObjectDeep(['a.b[0].c'.'a.b[1].d'], [1.2]);
// => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
Copy the code
- Xor (creates an array with unique values for a given array)
The API shines through
-
Remove (filter elements into two arrays)
-
SortedUniq (de-gravity, sort)
-
TakeRightWhile (Extracts elements from the last element of the array until predicate returns a false value)
-
UniqBy (de-duplication, sort)
A: Let’s have a Collection
Many of the Collection apis are impressive and can be used in real life development.
- ForEach (through the array or object) | forEachRight (antitone array or object again)
// It's a bit redundant to iterate through the array
lodash([1.2]).forEach((val) = > {
console.log(val)
})
// Iterate over the object
lodash({ a: 1.b: 2 }).forEach((val, key) = > {
console.log(val, key)
})
// native js **** note the order of array deconstruction
Object.entries({ a: 1.b: 2 }).forEach(([key, val]) = > {
console.log(val, key)
})
Copy the code
- Every (each element eligible) | some some element (eligible) | filter (filter) | find (find) first | findLast (find the last one) | includes (ha an element). Nice: You can pass in an object for matching
console.log(lodash([true.1.null.'yes']).every(Boolean)) // false
/ / equivalent
console.log([true.1.null.'yes'].every(Boolean)) // false
const users = [
{ user: 'barney'.age: 40.active: false },
{ user: 'fred'.age: 40.active: false},]// ******* a dazzling usage ********
console.log(lodash(users).every({ active: false.age: 40 })) // true
/ / equivalent
console.log(users.every((item) = > item.active === false && item.age === 40)) // true
console.log(lodash.find(users, { user: 'fred' }) === users[1]) // true
console.log(lodash.filter(users, { user: 'fred' })) // object for ['fred']
console.log(lodash.some(users, { user: 'fred' })) // true
Copy the code
- groupBy
const users = [
{ id: 'a'.age: 40.height: 1 },
{ id: 'b'.age: 39.height: 2 },
{ id: 'c'.age: 38.height: 2 },
{ id: 'd'.age: 40.height: 2},]console.log(lodash.groupBy(users, 'age'))
/ / to grouping children by age: {38: obj for [' a '], 39: obj for [' b '], 40: obj for [' c ', 'd']}
console.log(lodash.groupBy(users, ({ age, height }) => age + height))
/ / to grouping children by age + height results: {40: obj for [' c '], 41: obj for [' a ', 'b'], 42: obj for [' d ']}
Copy the code
-
InvokeMap (Decompose item: loop calls to methods that return values instead of collection items)
-
KeyBy (Generated objects: objects that make up the aggregation; The key value comes from the callback, and the callback parameter is the corresponding collection item. The value for the item)
-
OrderBy | sortBy (sorting: sort can specify more than one field, have the priority; Can control ascending and reverse order)
-
Partition: return true item array, false item array based on the value returned by the callback.
-
Reject (Find a collection of items that do not meet the criteria, similar! The filter)
-
Sample (draw lots: pick one at random from the set)
-
SampleSize (draw lots: select n randomly from a set)
-
Shuffle.
B) Function C) Function D) Function
The following list is the actual development of more application scenarios of the API, the specific usage will not do demo, can refer to the official website API.
- After (n, func) : The call is executed n times before func can be executed
- Before (n, func) : no func is executed after n calls. The return value after n calls is the NTH return value
- Curry | curryRight: curry
- Debounce: stabilization
- Defer: Defer the call
func
Until the current stack is cleared - Throttle: throttle
- Unary: Creates a function that takes at most one argument, ignoring the extra arguments
Six, Lang
Lang is mostly a judgment type API, the general isXxx judgment type API will not be described too much. Here are some useful apis.
- Clone series: Clone, cloneDeep, cloneWith, cloneDeepWith
- Eq: Judge equality, can judge NaN
- IsEqual: Identifies the equal value of two objects that can be enumerated. Note that it cannot be used to compare DOM objects
- IsEqualWith: customizes the isEqual comparison
- IsMatch: Checks that two partially enumerable values are equal
- IsMatchWith: Compares isMatch customization
Seven, Math
MaxBy (maximum) | minBy (minimum) | meanBy (draw) | sumBy (sum)
const users = [
{ id: 'b'.age: 39.height: 2 },
{ id: 'a'.age: 40.height: 1 },
{ id: 'c'.age: 38.height: 2 },
{ id: 'd'.age: 40.height: 2},]console.log(lodash.maxBy(users, 'age'))
// obj for 'a'
console.log(lodash.maxBy(users, ({ age, height }) => age + height))
// obj for 'd'
Copy the code
A: What’s the Number
- InRange: Indicates whether the value is greater than or equal to or less than or equal to. Improved implementation isInRange
@param string * demo: * const ten = 10 * ten.isinrange ('[1,10]') // true * ten.isinrange ('[1,10]') // false */
Number.prototype.isInRange = function (range = '[1, 10]') {
// 1. The range should be checked
const val = this.valueOf()
const isStartEqual = range.startsWith('[')
const isEndEqual = range.endsWith('] ')
let [start, end] = range
.slice(1, range.length - 1) // remove the first and last symbols '1,10'
.split(', ') // Cut string ['1', '10']
.map(Number) // Convert numbers [1, 10]
start > end && ([start, end] = [end, start]) // Start < end
const isGt = isStartEqual ? val >= start : val > start // >start
const isLt = isEndEqual ? val <= end : val < end // <end
return isGt && isLt
}
const ten = 10
console.log(ten.isInRange('[1, 10]')) // true
console.log(ten.isInRange('[1, 10)')) // false
Copy the code
9. Object
The following is a list of the most impressive apis
- The at | get: string key link
const object = { a: [{ b: { c: 3}},4]}console.log(lodash.at(object, ['a[0].b.c'.'a[1]']))
/ / [3, 4]
console.log(lodash.at(object, 'a[0].b.c'))
/ / [3]
console.log(lodash.get(object, 'a[0].b.c'))
/ / 3
Copy the code
- DefaultsDeep: Sets the default value for deep
const defaultData = { a: { b: 1.c: 3}}/ / the default value
const settingData = { a: { b: 2}}// Set the value
Object structures work well when objects have only one level, similar to lodash.defaults
// When the object level is more than one level, the default value of depth is washed out
constmergeData = { ... defaultData,// Default values are placed first. settingData, }console.log(mergeData)
// {a:{b:2}}
// Changes settingData, so get a copy
const mergeDataGood = JSON.parse(JSON.stringify(settingData))
lodash.defaultsDeep(mergeDataGood, defaultData) // The default value is at the end
console.log(mergeDataGood)
// {a:{b: 2, c: 3}}
Copy the code
- If there is a chain of properties from the | hasIn: judgment. Sometimes concatenation is needed to avoid code errors:
const dValue = a&&a.b&&a.b.c&&a.b.c.d
.ES2020
Operator has been finalized to add:? .
To solve the above problems. The above equivalent is written as:const dValue = a? .b? .c? .d
const obj = { a: { b: { c: { d: 'dValue'}}}}const obj2 = {}
console.log(lodash.has(obj,'a.b.c.d')) // true
console.log(lodash.has(obj2,'a.b.c.d')) // false
Copy the code
-
Invert: key-value invert: returns the value key of the old object.
-
InvertBy: similar to invert, handle keys of new objects.
-
MapKeys: handles the key of an object, generating a new object;
-
MapValues: process the object value and generate a new object;
-
The merge | mergeWith: object merge
var object = {
a: [{ b: 2 }, { d: 4}].obj: { key1: 'value1'.key2: 'value2'}},var other = {
a: [{ c: 3 }, { e: 5}].obj: { key1: 'valueOther1'.key3: 'valueOther2'}},console.log(lodash.merge(object, other))
/** { a: [ { b: 2, c: 3 }, { d: 4, e: 5 }, ], obj: { key1: 'valueOther1', key2: 'value2', key3: 'valueOther2' }, } */
Copy the code
- Omit | omitBy: rejecting object properties. It is used in scenarios where data is extracted and saved to the back end, the back end verification is strict, and redundant fields are not allowed.
const model = {
key1: 'value1'.// Data that needs to be sent to the back end
key2: 'value2'.key3: 'value3'.pageKey1: 'pageValue1'.// The field used by the page
pageKey2: 'pageValue2'.pageKey3: 'pageValue3',}// 1
const postData1 = {
key1: model.key1,
key2: model.key2,
key3: model.key3,
}
// omit
const postData2 = lodash.omit(model, ['pageKey1'.'pageKey2'.'pageKey3'])
// omitBy // Discard key containing page field
const postData3 = lodash.omitBy(model, (value, key) => key.includes('page'))
console.log(lodash.isEqual(postData1, postData2)) // true
console.log(lodash.isEqual(postData1, postData3)) // true
Copy the code
-
Pick | pickBy: selected object properties, functions and omit | omitBy instead. Use pick when there are more attributes to cull than to keep
-
Set: key link setting value, corresponding to GET
10 and Seq
There are too many apis, so here are just the ones that make Seq stand out
- Chain: Resolved that Lodash cannot be called chained
var users = [
{ user: 'barney'.age: 36 },
{ user: 'fred'.age: 40 },
{ user: 'pebbles'.age: 1},]const first = lodash
.chain(users)
.sortBy('age')
.map(function (o) {
return o.user + ' is ' + o.age
})
.head()
.value() // Note that.value() is run to get the result
console.log(first) // pebbles is 1
Copy the code
String String
Lodash’s String API is mostly an API for converting different values, such as uppercase, camel, HTML attribute, underscore concatenation, all lowercase, lowercase, encoding, padding, whitespace, etc.
The only API that shines: Template. It can be applied to dynamic internationalization and splicing internationalization
const compiled = lodash.template('hello <%= user.name %>! ')
console.log(compiled({ user: { name: 'fred'}}))// hello fred!
Copy the code