美文网首页
lodash 常用方法

lodash 常用方法

作者: 肥羊猪 | 来源:发表于2021-07-12 11:01 被阅读0次

对数据,特别是数组和对象进行各种读写等操作:比如去重,拷贝,合并,过滤,求交集,求和等等
官网:https://www.lodashjs.com/

omit, cloneDeep

使用:

cnpm i lodash -S
// 全局使用
import _ from 'lodash'
Vue.prototype._ = _
// 局部使用
let _ = require('lodash')

Create:

创建一个数组,元素为0, 1, 2, ... , 23
_.range([start=0], end, [step=1])
let arr = _.range(24)
console.log(arr) // [0, 1, 2, 3, ... , 23]
//创建一个数组,元素为100, 100, 100, 100, 100
_.fill(array, value, [start=0], [end=array.length])
let arr = _.fill(Array(5), 100)
console.log(arr) // [100, 100, 100, 100, 100]

Read:

//获取数组中最后一个元素
_.last(array)
let arr = [1, 2, 3, 4, 5]
let lastElement = _.last(arr) 
console.log(lastElement) // 5
//获取数组中倒数第二个元素
_.nth(array, [n=0])
let arr = [1, 2, 3, 4, 5]
let lastSecondElement = _.nth(-2) 
console.log(lastSecondElement) // 4
//获取对象数组中某一同名属性的属性值集合
.map(collection, [iteratee=.identity])
let users = [{
      id: 12,
      name: 'Adam',
      hobbies: [
        {name: 'running', index: 100},
        {name: 'cycling', index: 95}
      ]
   },{
      id: 14,
      name: 'Bob',
      hobbies: [
        {name: 'movie', index: 98},
        {name: 'music', index: 85}
      ]
   },{
      id: 16,
      name: 'Charlie',
      hobbies: [
       {name: 'travelling', index: 90},
       {name: 'fishing', index: 88}
      ]
   },{
      id: 18,
      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) // [12, 14, 16, 18]
console.log(mostFavouriteHobbies) // ["running", "movie", "travelling", "walking"]
//获取对象数组中某一属性值最大的对象
.maxBy(array, [iteratee=.identity])
let arr = [{a:1, b: 2, c: {d:4}}, {a:3, b: 4, c: {d:6}}]
let maxBObj = _.maxBy(arr, 'b')
console.log(maxBObj) // {a: 3, b: 4, c: {d: 6}}
//找出两个数组中元素值相同的元素
_.intersection([arrays])
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(array)
let numbers = [1, 2, 3, 4, 5]
let average = _.mean(numbers)
console.log(average) // 3
//求对象数组中某个属性值的平均数

.meanBy(array, [iteratee=.identity])
let objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]
let average = _.meanBy(objects, 'n')
console.log(average) // 5
//获取数组中前n个元素,不改变原数组

_.take(array, [n=1])
let arr = [1, 2, 3, 4, 5]
let part1Arr = _.take(arr, 4)
let part2Arr = _.take(arr, 6)
let part3Arr = _.take([], 5)
console.log(part1Arr) // [1, 2, 3, 4]
console.log(part2Arr) // [1, 2, 3, 4, 5]
console.log(part3Arr) // []

Delete: 删除数组中值为false的元素

_.compact(array)
let arr = [0, 1, false, 2, '', 3, null, undefined, NaN]
let truthyArr = _.compact(arr) 
console.log(truthyArr) // [1, 2, 3]

Format:

//去重。
_.uniq(array)
let arr = [2, 1, 2, '2', true]
let uniqArr = _.uniq(arr)
console.log(uniqArr) // [2, 1, '2', true]
//排序。对象数组,根据对象中的某个属性的值,升序或降序排序

.orderBy(collection, [iteratees=[.identity]], [orders])
let users = [
  {user: 'Tom', age: 25},
  {user: 'Amy', age: 23},
  {user: 'Perter', age: 22},
  {user: 'Ben', age: 29}
]
let sortedUsers = _.orderBy(users, 'age', 'desc')
console.log(sortedUsers)
// [{user: "Ben", age: 29}, {user: "Tom", age: 25}, {user: "Amy", age: 23}, {user: "Perter", age: 22}]
//分割数组[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]为 [1, 2, 3, 4, 5] 和 [6, 7, 8, 9, 10]

_.chunk(array, [size=1])
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let [left, right] = _.chunk(arr, 5)
console.log(left) // [1, 2, 3, 4, 5]
console.log(right) // [6, 7, 8, 9, 10]
//脱掉一层[]

_.flatten(array)
let address = {
  '江苏省': ['南京市', '苏州市'],
  '浙江省': ['杭州市', '绍兴市']
}
let cities = _.flatten(_.values(address))
console.log(cities) // ["南京市", "苏州市", "杭州市", "绍兴市"]
将多维数组转为一维数组
_.flattenDeep(array)
let flattenedArr = _.flattenDeep([1, [2, [3, [4]], 5]]);
console.log(flattenedArr) // [1, 2, 3, 4, 5]

Object:

Create
//通过数组["x", "y"] 和 数组[10, 10] 创建对象 {x: 10, y: 10}
_.zipObject([props=[]], [values=[]])
let keys = ["x", "y"]
let values = [10, 10]
let obj = _.zipObject(keys, values) 
console.log(obj) // {x: 10, y: 10}
//合并对象

_.assign(object, [sources])
let desObj = {name: '', gender: 'male', job: 'developer'}
let sourceObj = {name: 'Tom', job: ''}
let mergedObj = _.assign(desObj, sourceObj)
console.log(mergedObj) // {name: "Tom", gender: "male", job: ""}
//深拷贝对象

_.cloneDeep(value)
let sourceObj = {department_id: 1, permissions: {management: [1, 2, 3, 4], store: [11, 12, 13, 14]}}
let desObj = _.cloneDeep(sourceObj)
desObj.permissions.store.push(15, 16)
console.log(desObj)
// {department_id: 1, permissions: {management: [1, 2, 3, 4], store: [11, 12, 13, 14, 15, 16]}}
console.log(sourceObj)
// {department_id: 1, permissions: {management: [1, 2, 3, 4], store: [11, 12, 13, 14]}}
//合并多个对象中key值相同的键值对

_.merge(object, [sources])
let obj1 = {'9': {name: '乐购超市'}}
let obj2 = {'9': {storeToken: 'xxx'}}
let obj3 = {'9': {storePosition: 'Hangzhou'}}
let mergedObj = _.merge(obj1, obj2, obj3) 
console.log(mergedObj)
// 9: {name: "乐购超市", storeToken: "xxx", storePosition: "Hangzhou"}

Read:

判断对象中是否有某个属性
_.has(object, path)
let obj = {a: [{b: {c: 3}}]}
let hasC = _.has(obj, 'a[0].b.c')
console.log(hasC) // true
//获取对象中的某个属性的值

_.get(object, path, [defaultValue])
let obj = {a: [{b: {c: 3}}]}
let c = _.get(obj, 'a[0].b.c')
console.log(c) // 3

Update:

设置对象中的某个属性的值
_.set(object, path, value)
let obj = {a: [{b: {c: 3}}]}
let newObj = _.set(obj, 'a[0].b.c', 4);
console.log(obj.a[0].b.c); // 4
//对多个对象相同属性的属性值求和。

let customers = {
  new_customer: {0: 33, 1: 5, ... , 23: 0},
  old_customer: {0: 22, 1: 7, ... , 24: 0}
}
let customer = {}
let keys = _.keys(customers.new_customer)
let values = _.values(customers)
_.map(keys, key => {
  customer[key] = _.sumBy(values, key)
})
customers.customer = customer
console.log(customers)
// console
{
  customer: {0: 55, 1: 12, ... , 23: 0}
  new_customer: {0: 33, 1: 5, ... , 23: 0}
  old_customer: {0: 22, 1: 7, ... , 23: 0}
}

Number:

生成一个随机数,范围n~m
_.random([lower=0], [upper=1], [floating])
let random1 = _.random(2, 5)
let random2 = _.random(5)
console.log(random1) // 2, 3, 4, 5
console.log(random2) // 0, 1, 2, 3, 4, 5

Data Type

判断数据类型
_.isNumber(value)
_.isInteger(value)
...
_.isPlainObject(value)
let variable = 'hello';
// Number
console.log(_.isNumber(variable));
// Integer
console.log(_.isInteger(variable));
// Boolean
console.log(_.isBoolean(variable));
// String
console.log(_.isString(variable));
// Null
console.log(_.isNull(variable));
// Undefined
console.log(_.isUndefined(variable));
// Array
console.log(_.isArray(variable));
// Function
console.log(_.isFunction(variable));
// Object
console.log(_.isPlainObject(variable));
// Date
console.log(_.isDate(variable));
// DOM element
console.log(_.isElement(variable));
//数据类型转换
_.toArray
_.toArray('abc') // ["a", "b", "c"]
_.toInteger
_.toInteger(3.2); // 3
_.toInteger('3.2'); // 3
_.toNumber
_.toNumber('3.2') // 3.2
_.toString
_.toString(1); // "1"
_.toString([1, 2, 3]); // "1,2,3"

Util

重复多次某个元素
.times(n, [iteratee=.identity])
const dateParams = _.times(2, () => '2018-08-27');
console.log(dateParams) // ["2018-08-27", "2018-08-27"]

相关文章

  • lodash常用方法

    1. _.chunk(array, [size=1]) 将数组(array)拆分成多个size长度的区块,并将这...

  • lodash常用方法

    找数组中的相同key项的对象() intersectionBy 去重uniqBy 返回符合元素的 index,否则...

  • Lodash 常用方法

    Array .compact(array) 创建一个新数组,包含原数组中所有的非假值元素。例如false, nul...

  • lodash常用方法

    1._.get说明: 其实就是如果没有这个值以后就会返回undefined,而不会像js中没有这个值就会报错 2....

  • lodash 常用方法

    数组对象根据某一个值去重 数组去重 两个数组对象对比根据某一个值去重 若干数组并集,交集,补集 陆续更新

  • lodash 常用方法

    对数据,特别是数组和对象进行各种读写等操作:比如去重,拷贝,合并,过滤,求交集,求和等等官网:https://ww...

  • lodash常用方法

    https://www.cnblogs.com/t-sun-j/p/10642568.html[https://w...

  • lodash常用方法合集

    集合 1 _.map(collection, [iteratee=_.identity]) 1.1 定义 创建一个...

  • lodash中常用的方法

    lodash会拷贝一份新数组,不会对之前的数组进行影响 数据的基础处理 浅拷贝&&深拷贝 数组的分割,将数组(ar...

  • 分享几个用于深复制的方法

    本篇摘要:主要分享了 JS 中常用的几种深复制方法,有来自于vuex``jQuery``JSON``lodash`...

网友评论

      本文标题:lodash 常用方法

      本文链接:https://www.haomeiwen.com/subject/dbsrpltx.html