lodash常用的方法(附在实际项目中的使用心得) - 简书

const _ = require('lodash')

1.assign merge

const aa = _.assign({},{a:1},{a:2},{b:3})
//{a:2,b:3}
const bb = _.merge({},{a:1},{a:2},{b:3})
//{a:2,b:3}
const a1 = _.assign({},{a:1},{b:{a:1,b:2}},{b:{a:3}})
//{a:1,b:{a:3}}

const a2 = _.merge({},{a:1},{b:{a:1,b:2}},{b:{a:3}})
//{a:1,b:{a:3,b:2}}

相同之处:

  • 都可以用来合并对象
  • 都会修改原来的对象 (如果原来的对象是作为函数的第一个参数的话)
    不同之处
  • assign 函数不会处理原型链上的属性,也不会合并相同的属性,而是用后面的属性值覆盖前面的属性值
  • merge 遇到相同属性名的时候,如果属性值是纯对象或集合的时候,会合并属性值
  1. mergeWith
var object = { 'a': [3], 'b': [5] };
var other = { 'a': [6], 'b': [7] };
function foo (a,b) {
    if (_.isArray(a)) {
        return a.concat(b)
    }
}
function foo5 (a,b) {
    return _.toNumber(a) + _.toNumber(b)
}
const a3 = _.merge(object,other)
//{'a':[6],'b':[7]}
const a4 = _.mergeWith(object,other)
//{'a':[6],'b':[7]}
const a5 = _.mergeWith(object,other,foo)
//{'a':[3,6],'b':[5,7]}
const aaa = _.mergeWith(object,other,foo5)
//{'a':9,'b':12}
  1. sumBy
var arrs = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
var a6 = _.sumBy(arrs, k => k.n)  //20
var aa6 = _.sumBy(arrs,'n')  //20
// console.log(aa6);

var ccc = _.sum([3,16,15,20])
// console.log(ccc);
  1. sortBy
var users = [
    { 'user': 'barney',  'age': 36 },
    { 'user': 'fred',    'age': 40 },
    { 'user': 'pebbles', 'age': 1 }
  ];

  var youngest = _
  .chain(users)                         
  .sortBy('age')
  .value()
  console.log(youngest);    
//[ { user: 'pebbles', age: 1 },
// { user: 'barney', age: 36 },
// { user: 'fred', age: 40 } ]
  
// _.chain(arr)
//   LodashWrapper {
//     __wrapped__:   [ { user: 'barney', age: 36 },
//        { user: 'fred', age: 40 },
//        { user: 'pebbles', age: 1 } ],
//     __actions__: [],
//     __chain__: true,
//     __index__: 0,  __values__: undefined }
  var a7 = _.sortBy(users,'age')
  1. flatten
  var arr = [1,2,[3,4,[5],6]]
  var a8 = _.flatten(arr)  //[ 1, 2, 3, 4, [ 5 ], 6 ]
  var a9 = _.flattenDeep(arr)  //[ 1, 2, 3, 4, 5, 6 ]
  var a10 = _.flattenDepth(arr,2)  //[ 1, 2, 3, 4, 5, 6 ]
  1. 数组去重
  var arr2 = [12,14,11,12,12,1,14,16,17,22,2,11,12]
  var a11 = Array.from(new Set(arr2))
  var a12 = [...new Set(arr2)]
  var a13 = _.uniq(arr2)  //[ 12, 14, 11, 1, 16, 17, 22, 2 ]
  var arrObj = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 },{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
  var a14 = _.uniqWith(arrObj, _.isEqual)  //[ { x: 1, y: 2 }, { x: 2, y: 1 } ]
  1. isEqual
var object = { 'a': 1, 'b':2};
var other = { 'a': 1,'b':2 };
 
var a15 = _.isEqual(object, other);  //true

var a16 = _.isEqual([1,[2],2],[1,[2],2])  //true
  1. 其他
var a17 = _.random(1, 5,true);
// console.log(a17);
var a18 = _.inRange(5,1,10)  //true

var a19 = _.clamp(90, 5, 100)  //90

var a20 = _.min([14,12,11,15,14,22,10,34,12])  //10

var objects = [{ 'n': 4 }, { 'n': 2 },{'n':5},{'n':3}];
 
var a21 = _.minBy(objects,'n')  //{ n: 2 }   
// _.maxBy()
var a22 = _.minBy(objects,o => o.n)  //{ n: 2 }
console.log(a22);
  1. 深拷贝
_.cloneDeep()
var original = { foo: "bar" };
var newObj = _.cloneDeep(original)
original.foo = 'aaa'
console.log(original);  //{ foo: 'aaa' }
console.log(newObj);  //{ foo: 'bar' }
  1. 浅拷贝
_.clone()
var original1 = { foo: "bar" };
var newObj1 = _.clone(original)
original1.foo = 'aaa'
console.log(original1);  //{ foo: 'aaa' }
console.log(newObj1);  //{ foo: 'aaa' }
  • 含sorted的方法接受有序数组
  • 同名含By的方法额外接受一个迭代器参数
  • 同名含Last的方法返回的是符合筛选条件元素的最后一个
  1. reduce
  • 通过 iteratee 遍历集合中的每个元素。 每次返回的值会作为下一次 iteratee 使用。
  • 如果没有提供accumulator(第三个参数,即初始值),则集合中的第一个元素作为 accumulator。
  • 常见的错误是忽略了返回结果(return result)和没有传入函数的第三个参数(默认值)
var users = [
    { name: "John", age: 30 },
    { name: "Jane", age: 28 },
    { name: "Bill", age: 65 },
    { name: "Emily", age: 17 },
    { name: "Jack", age: 30 }
]
var finalRes = _.reduce(users,(result,user) => {
    if (user.age > 17 && user.age< 66) {
        (result[user.age] || (result[user.age] = [])).push(user)
    }
    return result
},{})
// { '28': [ { name: 'Jane', age: 28 }],
//   '30': [ { name: 'John', age: 30 }, { name: 'Jack', age: 30 } ], 
//   '65': [ { name: 'Bill', age: 65 }] 
// }
  1. 返回一个新的联合数组。去重
var b1 = _.union([1],[1,2],[1,2,3],[3,6,9])  //[ 1, 2, 3, 6, 9 ] 
var bb2 = _.union([1,2,3,1,2,1,11,2,3])  //[ 1, 2, 3, 11 ]
var b2 = _.unionBy([2.1], [1.2, 2.3,2.4,3.1], Math.floor);  //[ 2.1, 1.2, 3.1 ]
var b3 = _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 },{'x':3}],[{'x':2}] ,'x');
//[ { x: 1 }, { x: 2 }, { x: 3 } ]
var b4 = _.unionBy([{'x':1},{'x':2},{'x':3},{'x':3},{'x':1}],'x')
//[ { x: 1 }, { x: 2 }, { x: 3 } ]
var b5 = _.unionBy([{'x':1},{'x':2},{'x':3},{'x':3},{'x':1}],a=> a.x)
//[ { x: 1 }, { x: 2 }, { x: 3 } ]
var b6 = _.uniq([1],[1,2],[1,2,3],[3,6,9])  //1
var b7 = _.uniq([1,2,3,1,2,1,11,2,3])  //[ 1, 2, 3, 11 ]
var b8 = _.uniqBy([{ 'x': 2 }, { 'x': 1 },{'x':3},{'x':1},{'x':2}],'x')
//[ { x: 2 }, { x: 1 }, { x: 3 } ]

总结:union和uniq的区别:union支持多个数组去重,uniq只能是一个数组
13.fromPairs和toPairs

var b9 = _.fromPairs([['fred', 30], ['barney', 'a'],['some',1],['a','c']]);
//{ fred: 30, barney: 'a', some: 1, a: 'c' }
var b10 = _.toPairs({fred: 30, barney: 'a', some: 1, a: 'c' })
var b11 = Object.entries({fred: 30, barney: 'a', some: 1, a: 'c' })
//[ [ 'fred', 30 ], [ 'barney', 'a' ], [ 'some', 1 ], [ 'a', 'c' ] ]
  1. mapValues
var users = {
    'fred':    { 'user': 'fred',    'age': 40 },
    'pebbles': { 'user': 'pebbles', 'age': 1 }
  };
var c1 = _.mapValues(users,'age')  //{ fred: 40, pebbles: 1 }
  1. pickBy
    _.omit是pick的反向
var object = { 'a': 1, 'b': '2', 'c': 3 };
var c2 = _.pick(object,['a','c'])  //{ a: 1, c: 3 }
var c3 = _.pickBy(object, _.isString)  //{ b: '2' }
console.log(c3);
  1. drop
    去除array前面的n个元素
var c3 = _.drop([1, 2, 3], 2);  //[ 3 ]
console.log(c3);
  1. shuffle()
    创建一个被打乱值的数组(随机打乱)
var c4 = _.shuffle([1,5,11,4,3,6])   //[ 1, 11, 6, 5, 3, 4 ]  [ 4, 6, 1, 3, 11, 5 ]
var c5 = _.shuffle([['fred', 30], ['barney', 'a'],['some',1],['a','c']])  
//[ [ 'some', 1 ], [ 'a', 'c' ], [ 'barney', 'a' ], [ 'fred', 30 ] ]
var c6 = _.shuffle([{ 'user': 'fred'},{'age': 40 },{ 'user': 'pebbles'}])
//[ { user: 'pebbles' }, { age: 40 }, { user:'fred' } ]
console.log(c6);
  1. sample
    随机获取数组中的某一项,attr2:随机获取的个数
var ccc = _.sample(["lisong", "heyan",'A','C'], 1);
console.log(ccc);  //heyan
  1. map
let ownerArr = [
    {
        "owner": "Colin",
        "pets": [{"name":"dog1"}, {"name": "dog2"}]
    }, 
    {
        "owner": "John",
        "pets": [{"name":"dog3"}, {"name": "dog4"}]
    }];
console.log(_.map(ownerArr, 'pets[1].name')); // 循环找寻深度数组的值 [ 'dog2', 'dog4' ]
console.log(_.map(ownerArr,o=>o.pets[1].name))  // [ 'dog2', 'dog4' ]

var users = [
    { 'user': 'barney' },
    { 'user': 'fred' }
  ];
   
 var c7 =  _.map(users, 'user');  //[ 'barney', 'fred' ]
 var c8 = _.map(users,o=>o.user)  //[ 'barney', 'fred' ]

  1. uniqueId
  var c9= _.uniqueId('userId')  //userId1
  var c10 = _.uniqueId('userId') //userId2
  var c11 = _.uniqueId('userId') //userId3
  1. find、filter
let F = [
    {id: 0, name: "aaa", age: 33},
    {id: 1, name: "bbb", age: 25},
    {id: 2, name: "ccc", age: 25}
];
var sss = _.find(F, ["id", _.max(_.map(F, "id"))]); //json字符串中某一项最大的
// console.log(sss);  // { id: 2, name: 'ccc', age: 25 }
var ss1 = _.find(F, ["id", 2]) // { id: 2, name: 'ccc', age: 25 }
// console.log(ss1);
var ss2 = _.filter(F, ["id", 2])  // [ { id: 2, name: 'ccc', age: 25 } ] 返回一个新的过滤后的数组。
var ss3 = _.filter(F, ["id", _.max(_.map(F, "id"))])  // [ { id: 2, name: 'ccc', age: 25 } ]

var d11 = Array.prototype.slice.apply(["a","b"]);       
console.log(d11);

// Array.prototype.slice.call(arguments)
var d13  = new Array(3)
console.log(d13);
  1. compact
  • 数组去空(去除false, null, 0, "", undefined, 和 NaN)
_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]
    • *

最后,还有一个特别好用的方法_.groupBy()
使用场景如下图:我需要将数组中每个对象按照id相同的,组成一个二维数组

image.png

将上图转换成下图这种数据格式:

image.png

  1. 使用_.groupBy()得到如下图的数据结构:
var courseGroup = _.groupBy(arr, 'lesson.courseSession.objectId')
或
var courseGroup = _.groupBy(arr, e => {
  return e.lesson.courseSession.objectId
)

image.png

2.使用Object.values()即可得到啦

var finalData = Object.values(courseGroup)

Original url: Access
Created at: 2019-09-25 10:10:07
Category: default
Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论