lodash中文文档如今我只找到了3.10.x版本,如今lodash已更新到4.17.x了,很多文档已逾期。而且lodash中api太多,有时候经常运用的几个我老是记不住名字,在这里贴出来,轻易本身和人人。
原生用法
直接运用的API
_.reject
依据前提去除某个元素。
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的数组,挑选第一个参数中的值并返回
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)
_.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,要处置惩罚一下
_.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
依据前提过滤出相符前提的元素,返回新数组
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}
//]