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 = {
//    aaa: {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}
//]

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值