Lodash經常使用API筆記

lodash中文文檔目前我只找到了3.10.x版本,如今lodash已經更新到4.17.x了,好多文檔已通過期。並且lodash中api太多,有時候經常使用的幾個我老是記不住名字,在這裏貼出來,方便本身和你們。javascript


原生用法

直接使用的APIjava

_.reject

根據條件去除某個元素。json

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

//bar = [{id: 1, name: "bbb", age: 25}]

_.pick

根據第二個參數的key的數組,篩選第一個參數中的值並返回api

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

_.keys

返回object中的全部key數組

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

_.cloneDeep

深度拷貝,這個不用多說了吧,js中基礎類型之外的類型,都會默認拷貝備份
var bar = _.cloneDeep(foo)code

_.find

查找數組對象

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

注意一下若是沒找到的話,會返回undefined,要處理一下ip

_.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}
//}

_.filter

根據條件過濾出符合條件的元素,返回新數組class

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

_.map

從集合中挑出一個key,將其值做爲數組返回

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

_.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

_.pad/_.padStart/_.padEnd

在兩端、開頭、末尾補齊字符

var foo = "helloworld"
var bar = _.pad(foo, 14, '-')
//bar = --helloworld--
bar = _.padStart(foo, 14, '-')
//bar = ----helloworld
bar = _.padEnd(foo, 14, '-')
//bar = helloworld----

組合用法

若是說上面是基礎技能,那麼下面奉上幾個炫酷的組合技:

選出json數組中id最大的一項

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

ps:也能夠用maxBy某個key來代替

更新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}
//]
相關文章
相關標籤/搜索