lodash操作整理

lodash的所有函数都不会对原数据进行改变,都是复制出一个新的数据进行操作得到结果,类似immutable.js的理念去处理。其是一套javascript工具库,用于对数组、函数、对象、字符串等数据类型进行处理的函数。本文只是自己的学习的一个记录,以供自己理解及日后查阅,文字过于白话。

1、对数组进行切分,切成你想要的长度的多个数组(_.chunk),例如:

import _ from 'lodash'
let a = [1, 2, 3, 4, 5, 6];
_.chunk(a, 1) // [1] 和 [2] 和 [3] 和 [4] 和 [5] 和 [6]
_.chunk(a, 2) // [1, 2, 3] 和 [4, 5, 6]
_.chunk(a, 3) // [1, 2, 3] 和 [4, 5, 6]
_.chunk(a, 4) // [1, 2, 3, 4] 和 [5, 6]
_.chunk(a, 5) // [1, 2, 3, 4, 5] 和 [6]
_.chunk(a, 6) // [1, 2, 3, 4, 5, 6]

2、数组中去掉假值(false, null, 0, “”, ‘’, undefined, 和 NaN )(_.compact 注意:只能是数组,不能对象或者数组对象),例如

import _ from 'lodash'
let a = [1, 0, false, '', 2, 1, 3, 2, 4, 5]
//去重
let b = _.compact(a); // [1, 2, 3, 4, 5]

3、数组拼接其他数组或者其他值,变成一个新的数组(_.concat)

import _ from 'lodash'
_.concat(1, 2) // [1, 2]
_.concat(4, [3]) // [4, 3]
_.concat([33, 32], 21) // [33, 32, 21]
_.concat([1, 2], [3, 4]) // [1, 2, 3, 4]

4、数组进行过滤,排除一些不想要的值(_.difference _.differenceBy _.differenceWith)

import _ from 'lodash'
_.difference([1, 2, 3, 4], [2, 4]) // 排除2和4的数组,结果为: [1, 3]

_.differenceBy([1.1, 2.3, 3.7, 4.6, 5.3],[2.3, 7.4, 5.7], Math.floor) // 两个数组中的值经过Math.floor操作后,再进行排除操作,最后结果为: [1.1, 3.7, 4.6]
_.differenceBy([{
    
    'x': 1}, {
    
    'x': 2}], [{
    
    'x': 1}], 'x') // 结果为: [{'x': 2}]
_.differenceBy([{
    
    'x': 1, 'y': 3},{
    
    'x': 2, 'y': 2}], [{
    
    'y': 3}], 'y') // 结果为: [{'x': 2, 'y': 2}]

_.differenceWith([{
    
     'x': 1, 'y': 2 }, {
    
     'x': 2, 'y': 1 }], [{
    
     'x': 1, 'y': 2 }], _.isEqual) // [{ 'x': 2, 'y': 1 }]

未完待续

おすすめ

転載: blog.csdn.net/qq_37600506/article/details/109743857