項目裏常常用到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])