last
获取数组中最后一个元素
let arr = [1, 2, 3, 4, 5]
let last = _.last(arr)
console.log(last ) // 5
nth
获取数组中倒数第几个元素
let arr = [1, 2, 3, 4, 5]
let lastSecond = _.nth(-2)
console.log(lastSecond ) // 4
map
获取对象数组中某一同名属性的属性值集合,第一个参数是对象,第二个参数属性名
let users = [{
id: 1,
name: 'mickey',
hobbies: [
{name: 'running', index: 100},
{name: 'cycling', index: 95}
]
},{
id: 2,
name: 'jack',
hobbies: [
{name: 'movie', index: 98},
{name: 'music', index: 85}
]
},{
id: 3,
name: 'Bob',
hobbies: [
{name: 'travelling', index: 90},
{name: 'fishing', index: 88}
]
},{
id: 4,
name: 'David',
hobbies: [
{name: 'walking', index: 99},
{name: 'football', index: 85}
]
}
]
let userIds = _.map(users, 'id')
let mostFavouriteHobbies = _.map(users, 'hobbies[0].name')
console.log(userIds) // [1, 2, 3, 4]
console.log(mostFavouriteHobbies) // ["running", "movie", "travelling", "walking"]
intersection
找出两个数组中元素值相同的元素
let arr1 = [2, 1, {a: 1, b: 2}]
let arr2 = [2, 3, {a: 1, b: 2}]
let intersection = _.intersection(arr1, arr2)
console.log(intersection) // [2]
mean
求数值数组中元素值的平均数
let numbers = [1, 2, 3, 4, 5]
let average = _.mean(numbers)
console.log(average) // 3
menaBy
求对象数组中某个属性值的平均数
let objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]
let average = _.meanBy(objects, 'n')
console.log(average) // 5
unid、uniqBy
数组去重和数组中的对象去重
//普通的数据去重
let arrA = [1,1,2,2,3,4,5]
console.log(arrA.unid(arrA)) // [1,2,3,4,5]
//数组中对象得去重
let arrB = [{name:mickey},{name:mickey},{age:25}]
console.log(arrB.uniqBy(arrB,"name")) // [{name:mickey},{age:25}a]
cloneDeep
clone数据,类似于深拷贝。
let obj = [{loadsh:1},2,3,4]
let cloneObj = clone(obj)
console.log(cloneObj) // [{loadsh:1},2,3,4]
obj[0].loadsh = 3
console.log(cloneObj) // [{loadsh:3},2,3,4]
//clone拷贝的数据是浅拷贝
let obj = [{loadsh:1},2,3,4]
let cloneObj = cloneDeep(obj)
console.log(cloneObj) // [{loadsh:1},2,3,4]
obj[0].loadsh = 3
console.log(cloneObj) // [{loadsh:1},2,3,4]
//cloneDeep拷贝的数据是深拷贝
truncate
该函数可以截断string
字符串,如果字符串超出了限定的最大值,那么就会截断字符串,并且用omission替代,默认的omission为'...'。 结合ToolTip,可以在展示数据时很方便的处理数据。
获取对象中的某个属性的值
let obj = {a: [{b: {c: 3}}]}
let c = _.get(obj, 'a[0].b.c')
console.log(c) // 3
判断对象中是否有某个属性
let obj = {a: [{b: {c: 3}}]}
let hasC = _.has(obj, 'a[0].b.c')
console.log(hasC) // true
设置对象中的某个值
let obj = {a: [{b: {c: 3}}]}
let newObj = _.set(obj, 'a[0].b.c', 4);
console.log(obj.a[0].b.c); // 4