[转] Lodash常用API笔记

时间:2023-03-08 16:32:24

原生用法

直接使用的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}
//]