Lodash用来操作对象和集合,比Underscore拥有更多的功能和更好的性能。


官网:https://lodash.com/
引用:<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
安装:npm install lodash

首先通过npm安装lodash:
npm i --save lodash

在js文件中引用lodash:
var _ = require('lodash');

import * as _ from "lodash";

 目录

对象集合

  1. 获取对象中字段的集合 pluck map pick

  2. 查找第一个复合条件的对象 find

3. 排除不想要的字段们,不想要的字段作为参数传递 omit or function

4. 给对象元素添加新的字段,根据现有字段计算而得 extend
5. 更改对象某个字段的值,类似泛型 partial
6. 根据对象元素的某个字段进行分组 groupBy
7. 对某个字段求和 reduce

8. 对集合元素依次使用多个方法 filter和map

数组集合

1. map方法使用内置函数,计算每一个集合元素的大小 size
2. map方法使用内置函数,获取每个集合元素中的最小值 min
3. map方法使用内置函数,针对集合元素依次调用多个方法 flowRight first

对象集合

1. 获取对象中字段的集合 pluck map pick

1. 获取对象中某个字段的集合  pluck or map

var collection = [
    {name: '', age:45}
];
_.pluck(collection, 'age');  // [45]

// 也可以这样写:
_.map(collection, 'age');  // [45]

2. 获取想要的字段们, 多个  pick

const collection = [
   { name: '', age: 45 },
   { name: 'tt', age: 23, hua: 'hua' },
];
const tt = _.map(collection, (item) => { return _.pick(item, ['name', 'age']); }); console.log(tt); // [ {name: "", age: 45}, {name: "tt", age: 23} ]

2. 查找第一个复合条件的对象 find 

const collection = [
  { name: 'Cameron', supervisor: false },
  { name: 'Lindsey', supervisor: true },
  { name: 'Kenneth', supervisor: false },
  { name: 'Caroline', supervisor: true }
];

const app = _.find(collection, {supervisor:true});

//{ name: 'Lindsey', supervisor: true }
console.log(app);

3. 排除不想要的字段们,不想要的字段作为参数传递 omit or function

1. 排除不想要的字段们,不想要的字段作为参数传递  omit 

const collection = [
   { name: '', age: 45 },
   { name: 'tt', age: 23, hua: 'hua' },
];
const tt = _.map(collection, (item) => { return _.omit(item, ['name']); }); console.log(tt); // [ {age: 45}, {age: 23, hua: "hua"} ]

2. 排除不想要的字段们,通过函数 function

var collection = [
    {first:'',last:'',age:19},
    ...
];

//key 字段名称, value 字段对应的值
function invalidAge(value, key){
    return key === 'age' && value < 40;
}

_.map(collection, function(item){
    reutrn _.omit(item, invalidAge);
});

4. 给对象元素添加新的字段,根据现有字段计算而得  extend

var collection = [
    { name: 'Valerie', jqueryYears: 4, cssYears: 3 },
    { name: 'Alonzo', jqueryYears: 1, cssYears: 5 },
    { name: 'Claire', jqueryYears: 3, cssYears: 1 },
    { name: 'Duane', jqueryYears: 2, cssYears: 0 }
];

var result = _.map(collection, function(item){
   return _.extend({
       experience: item.jqueryYears + item.cssYears,
       speciality: item.jqueryYears >= item.cssYears ? 'jQuery' : 'CSS'
   }, item);
});

//[ { experience: 7,speciality: 'jQuery',name: 'Valerie',jqueryYears: 4,cssYears: 3 },...]
console.log(result);

5. 更改对象某个字段的值,类似泛型  partial

//this作为上下文对象有prop和value字段
//this的prop键值决定哪个字段需要实施加法
//item在这里会传入集合元素
function add(item){
    var result = _.clone(item);
    result[this.prop] += this.value;
    return result;
}

function upper(item){
    var result = _.clone(item);
    result[this.prop]=result[this.prop].toUpperCase();
    return result;
}

var collection = [
    { name: 'Gerard', balance: 100 },
    { name: 'Jean', balance: 150 },
    { name: 'Suzanne', balance: 200 },
    { name: 'Darrell', balance: 250 }
];

var mapAdd = _.partial(_.map, collection, add),
    mapUpper = _.partial(_.map, collection, upper);

//[ { name: 'Gerard', balance: 150 },
//    { name: 'Jean', balance: 200 },
//    { name: 'Suzanne', balance: 250 },
//    { name: 'Darrell', balance: 300 } ]
console.log(mapAdd({ prop: 'balance', value: 50 }));


//[ { name: 'GERARD', balance: 100 },
//    { name: 'JEAN', balance: 150 },
//    { name: 'SUZANNE', balance: 200 },
//    { name: 'DARRELL', balance: 250 } ]
console.log(mapUpper({ prop: 'name'}));

6. 根据对象元素的某个字段进行分组 groupBy

var collection = [
    { id: _.uniqueId('id-'), position: 'absolute', top: 12 },
    { id: _.uniqueId('id-'), position: 'relative', top: 20 },
    { id: _.uniqueId('id-'), position: 'absolute', top: 12 },
    { id: _.uniqueId('id-'), position: 'relative', top: 20 }
];

var result = _.groupBy(collection, 'position');

// { 
//   absolute: [ 
// { id: 'id-1', position: 'absolute', top: 12 },
// { id: 'id-3', position: 'absolute', top: 12 }
// ],
// relative: [
// { id: 'id-2', position: 'relative', top: 20 },
// { id: 'id-4', position: 'relative', top: 20 }
// ]
// } console.log(result); var result2 = _.indexBy(collection, 'id'); // {
// 'id-1': { id: 'id-1', position: 'absolute', top: 12 },
// 'id-2': { id: 'id-2', position: 'relative', top: 20 }, // 'id-3': { id: 'id-3', position: 'absolute', top: 12 }, // 'id-4': { id: 'id-4', position: 'relative', top: 20 }
// }
console.log(result2);

 

7. 对某个字段求和 reduce

1. 累加的初始值是数字 

var collection = [
    { ram: 1024, storage: 2048 },
    { ram: 2048, storage: 4096 },
    { ram: 1024, storage: 2048 },
    { ram: 2048, storage: 4096 }
];

var result1 = _.reduce(collection, function(result, item){
    return result+item.ram;
},0);  // 0是累加的初始值
//6144
console.log(result1);

var result2 = _.reduce(collection, function(result, item){
    return result+item.storage;
},0);  // 0是累加的初始值
//12288
console.log(result2);

2. 对某个字段求和,类似泛型 partial  reduce

function sum(a,b){
    return a+b[this.prop];
}

var collection = [
    { low: 40, high: 70 },
    { low: 43, high: 83 },
    { low: 39, high: 79 },
    { low: 45, high: 74 }
];

var reduceSum = _.partial(_.reduce, collection, sum, 0);

//167
console.log(reduceSum({ prop: 'low' }));

3. 累加的初始值是对象

var collection = [
    {hits: 2, misses: 4},
    {hits: 5, misses: 1},
    {hits: 3, misses: 8},
    {hits: 7, misses: 3}
];

var result = _.reduce(collection, function(result, item) {
    return {
        hits: result.hits + item.hits,
        misses: result.misses + item.misses
    };
}, { hits: 0, misses: 0 });

//{ hits: 17, misses: 16 }
console.log(result);

4. 自定义累加的算法

function add(a,b){
    return a+b;
}

var collection =[
    {wins:34, loses:21},
    {wins:58, loses:12},
    {wins:34, loses:23},
    {wins:40, loses:15},
];

var result1 = _.reduce(_.range(1,6),add);//[ 1, 2, 3, 4, 5 ]
console.log(result1);//15

var result2 =_.reduce(_.pluck(collection,'wins'),add);
console.log(result2);//166

5. 累加的字段是整型数组,对数组元素相加,把和最小所在的对象打印出来

//对象中的一个字段是数值数组
var collection = [
    { name: 'Madeline', scores: [ 88, 45, 83 ] },
    { name: 'Susan', scores: [ 79, 82, 78 ] },
    { name: 'Hugo', scores: [ 90, 84, 85 ] },
    { name: 'Thomas', scores: [ 74, 69, 78 ] }
];

//对对象item的scores字段所代表的数组数组求和
function score(item) {
    return _.reduce(item.scores, function(result, score) {
        return result + score;
    });
}

var result = _.min(collection, score);

//{ name: 'Madeline', scores: [ 88, 45, 83 ] }
console.log(result);

如果求最大,那就是:

var result = _.max(collection, score);

 

8. 对集合元素依次使用多个方法  filter和map

var collection = [
    { name: 'Karl', enabled: true },
    { name: 'Sophie', enabled: true },
    { name: 'Jerald', enabled: false },
    { name: 'Angie', enabled: false }
];

var result = _.flowRight(
    _.partialRight(_.map, 'name'),
    _.partialRight(_.filter, 'enabled')
)(collection);


//[ 'Karl', 'Sophie' ]
console.log(result);

 

数组集合

1. map方法使用内置函数,计算每一个集合元素的大小 size

var collection=[
    [1,2],
    [1,2,3],
    {first:1, second:2},
    {first:1, second:2,third:3}
];

var result = _.map(collection, _.size);

//[ 2, 3, 2, 3 ]
console.log(result);

2. map方法使用内置函数,获取每个集合元素中的最小值  min

const collection=[
    [2, 4, 5, 7, 8, 9],
    [12, 1, 55, 0, 38, 9],
    [22, 43, 15, 17, 28, 9],
];
console.log(collection);

// [2, 0, 9]
console.log(_.map(collection, _.min));

3. map方法使用内置函数,针对集合元素依次调用多个方法 flowRight first

// flowRight方法会依次调用其参数方法,先给每个一个元素内的元素排序,然后取出元素中的元素中的第一个。
var collection = [
    [ 'Evan', 'Veronica', 'Dana' ],
    [ 'Lila', 'Ronald', 'Dwayne' ],
    [ 'Ivan', 'Alfred', 'Doug' ],
    [ 'Penny', 'Lynne', 'Andy' ]
];

var result = _.map(collection, _.flowRight(_.first, function(item){
    return _.sortBy(item);
}));

//[ 'Dana', 'Dwayne', 'Alfred', 'Andy' ]
console.log(result);

 

 

参考:

https://www.bbsmax.com/A/Ae5RgnELdQ/

posted on 2020-01-10 11:20  云雀sunshine  阅读(1126)  评论(0编辑  收藏  举报