项目里常常用到Lodash,来作一个小小的概括总结吧!json
先要明白的是lodash的全部函数都不会在原有的数据上进行操做,而是复制出一个新的数据而不改变原有数据数组
接下来就是Lodash的引用,简单粗暴函数
一、_.forEach
遍历spa
_.forEach(agent,function(n,key) { agent[key].agent_id= agent[key].agent_name })
返回新的数组agent
二、_.compact
过滤假值 去除假(将全部的空值,0,NaN过滤掉)code
_.compact(['1','2',' ',0] //=>['1', '2']
三、_.uniq
数组去重 用法同上(将数组中的对象去重,只能是数组去重,不能是对象去重。)对象
_.uniq([1,1,3]) // => [1,3]
四、_.filter
和_.reject
过滤集合,传入匿名函数。(两者放在一块儿讨论的缘由是,两个函数相似但返回的值是相反。)继承
这两个过滤器,第二个参数值是false的时候返回是reject的功能,相反是true的时候是filter递归
_.filter([1,2],x => x = 1) // => [1] _.reject([1,2],x => x=1) // => [2]
五、_find
返回匹配的对象索引
附上官网的例子,参数能够是对象、数组、函数,注意它和_.filter
的区别,前者返回对象,后者返回数组ip
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'
六、_.map
和_.forEach
,数组遍历。(类似)
这两个方法ES6完美支持,因此通常就直接用原生的啦
七、_.merge
参数合并
递归地将源对象和继承的可枚举字符串监控属性合并到对象中,源对象从左到右引用,后续来源将覆盖之前来源的属性分配。
八、_.cancat
数组链接
var array = [1]; var other = _.concat(array, 2, [3], [[4]]); console.log(other); // => [1, 2, 3, [4]] console.log(array); // => [1]
可接受多个参数,将多个参数合并为一个数组元素
九、_.keys
,取出对象中全部key值组成的数组
这个方法也能够用Object.keys()
支持
十、_.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}
十一、_.cloneDeep
很少说,深拷贝,你值得拥有
十二、_.max/_.min/_.sum
数组中最大值、最小值、数组求和
var foo = [1, 2, 3, 4] var bar = _.max(foo) //bar = 4 bar = _.min(foo) //bar = 1 bar = _.sum(foo) //bar = 10
1三、_.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} //]
1四、_.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])