博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Lodash学习小记
阅读量:7009 次
发布时间:2019-06-28

本文共 2652 字,大约阅读时间需要 8 分钟。

项目里经常用到Lodash,来做一个小小的归纳总结吧!

那么,什么是Lodash呢

先要明白的是lodash的所有函数都不会在原有的数据上进行操作,而是复制出一个新的数据而不改变原有数据

接下来就是Lodash的引用,简单粗暴

clipboard.png

常用的Lodash方法

1、_.forEach遍历

_.forEach(agent,function(n,key) {    agent[key].agent_id= agent[key].agent_name})

返回新的数组agent

2、_.compact过滤假值 去除假(将所有的空值,0,NaN过滤掉)

_.compact(['1','2',' ',0]//=>['1', '2']

3、_.uniq 数组去重 用法同上(将数组中的对象去重,只能是数组去重,不能是对象去重。)

_.uniq([1,1,3])// => [1,3]

4、_.filter_.reject 过滤集合,传入匿名函数。(二者放在一起讨论的原因是,两个函数类似但返回的值是相反。)

这两个过滤器,第二个参数值是false的时候返回是reject的功能,相反是true的时候是filter

_.filter([1,2],x => x = 1)// => [1] _.reject([1,2],x => x=1)// => [2]

5、_find 返回匹配的对象

附上官网的例子,参数可以是对象、数组、函数,注意它和_.filter的区别,前者返回对象,后者返回数组

var users = [  { 'user': 'barney',  'age': 36, 'active': true },  { 'user': 'fred',    'age': 40, 'active': false },  { 'user': 'pebbles', 'age': 1,  'active': true }]; _.find(users, function(o) { return o.age < 40; });// => object for 'barney' // The `_.matches` iteratee shorthand._.find(users, { 'age': 1, 'active': true });// => object for 'pebbles' // The `_.matchesProperty` iteratee shorthand._.find(users, ['active', false]);// => object for 'fred'

6、_.map_.forEach,数组遍历。(相似)

这两个方法ES6完美支持,所以一般就直接用原生的啦

7、_.merge 参数合并

递归地将源对象和继承的可枚举字符串监控属性合并到对象中,源对象从左到右引用,后续来源将覆盖以前来源的属性分配。

8、_.cancat 数组连接

var array = [1];var other = _.concat(array, 2, [3], [[4]]); console.log(other);// => [1, 2, 3, [4]] console.log(array);// => [1]

可接受多个参数,将多个参数合并为一个数组元素

9、_.keys,取出对象中所有key值组成的数组

这个方法也可以用Object.keys()支持

10、_.pick这个一般是配合keys来使用的,可以取出对象内指定key值的成员们组成的新对象

let obj = {    name: 'john',    age: 20,    hobby: 'travelling'}let keys = ['name', 'age']let newObj = _.pick(obj, key)console.log(newObj)// => {name: 'john', age: 20}

11、_.cloneDeep 不多说,深拷贝,你值得拥有

12、_.max/_.min/_.sum 数组中最大值、最小值、数组求和

var foo = [1, 2, 3, 4]var bar = _.max(foo)//bar = 4bar = _.min(foo)//bar = 1bar = _.sum(foo)//bar = 10

13、_.keyBy 以某个属性为键,将数组转为对象

var foo = var foo = [    {id: 0, name: "aaa", age: 33},    {id: 1, name: "bbb", age: 25}]var bar = _.keyBy(foo, 'name')//bar = {//    aaa: {id: 0, name: "aaa", age: 33},//    bbb: {id: 1, name: "bbb", age: 25}//}

更新json数组中某一项的值

var foo = [    {id: 0, name: "aaa", age: 33},    {id: 1, name: "bbb", age: 25}]let list = _.keyBy(foo, 'id')list[0].name = "ccc"var bar = _.map(list)// bar = [//    {id: 0, name: "ccc", age: 33},//    {id: 1, name: "bbb", age: 25}//]

14、_.reduce 类似于累加的一个功能,遍历集合元素,每次返回的值会作为下一次迭代的初始值使用

调用4个参数:(collection, Function()[total, value, index|key, colletion], [accumulator])

挨个解释一下:

accumulator: 作为迭代函数的初始值使用,如果没有提供accumulator,则collection(集合)中的第一个元素作为初始值value:当前元素index|key:当前元素的索引collection:当前集合

比较一下ES6原生的reduce方法:

reduce(function(total,currentValue, index,arr),[initialValue])

转载地址:http://tbntl.baihongyu.com/

你可能感兴趣的文章