lodash日常常用操作

lodash的所有函数都不会对原数据进行改变,都是复制出一个新的数据进行操作得到结果,类似immutable.js的理念去处理。lodash是一套javascript工具库,用于对数组、函数、对象、字符串等数据类型进行处理的函数

1、对数组对象进行过滤(.filter,.reject),例如:

import _ from 'lodash'
let students = [
  {
    
    name: 'bob', age: 11, active: true},
  {
    
    name: 'bili', age: 20, active: false},
  {
    
    name: 'lili', age: 12, active: true}
]
//正向筛选出 active为 true的学生数组对象集合数据
_.filter(students, [active, true]); //objects for [{name: 'bob', age: 11, active: true},{name: 'lili', age: 12, active: true}]
//反向筛选出 active为true的学生数组对象集合数据
_.reject(student, [active, false]);//objects for [{name: 'bob', age: 11, active: true},{name: 'lili', age: 12, active: true}]

//筛选出 age小于15的学生数组对象集合数据
_.filter(students, function(item){
    
     return item.age < 15 });//objects for [{name: 'bob', age: 11, active: true},{name: 'lili', age: 12, active: true}]
//反向筛选出  age小于15的学生数组对象集合数据
_.reject(student, function(item){
    
     return item.age >= 15 });//objects for [{name: 'bob', age: 11, active: true},{name: 'lili', age: 12, active: true}]

2、取得数组对象中某些字段对应的值组成数组(_.map),例如

import _ from 'lodash'
let students = [
  {
    
    id:1, name: 'bob', age: 11, active: true},
  {
    
    id:2, name: 'bili', age: 20, active: false},
  {
    
    id:3, name: 'lili', age: 12, active: true}
]
//筛选出 students的id,组成数组
let ids = _.map(students, 'id'); // [1,2,3]

3、取得对象的key组成数组(和 Object.keys() 功能类似),例如

import _ from 'lodash'
let bob = {
    
    id:1, name: 'bob', age: 11, active: true}
//筛选出 students的id,组成数组
let bobKeys = _.keys(bob); // [1, 'bob', 11, true]

4、数组去重 (_.uniq 注意:只能是数组,不能对象或者数组对象),例如

import _ from 'lodash'
let a = [1,2,3,4,2,1,3,2,12,34]
//去重
let b = _.uniq(a); // [1,2,3,4,12,34]

5、数组中去掉假值(false, null, 0, “”, undefined, 和 NaN )(_.compact 注意:只能是数组,不能对象或者数组对象),例如

import _ from 'lodash'
let a = [1,0,false,'',2,1,3,2,4,5]
//去重
let b = _.compact(a); // [1,2,3,4,5]

猜你喜欢

转载自blog.csdn.net/qq_37600506/article/details/109738495
今日推荐