lodash 常用方法

挑选数据 .pluck 或者 .map

前面我们已经看到了很多用_.pluck来挑选数据的例子

var collection = [
       { name: 'Virginia', age: 45 },
       { name: 'Debra', age: 34 },
       { name: 'Jerry', age: 55 },
       { name: 'Earl', age: 29 }
];

_.pluck(collection, 'age');
   // → [ 45, 34, 55, 29 ]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

其实我们也可以用map来做同样的事情

var collection = [
       { name: 'Michele', age: 58 },
       { name: 'Lynda', age: 23 },
       { name: 'William', age: 35 },
       { name: 'Thomas', age: 41 }
];

_.map(collection, 'name');
   // →
   // [
   //   "Michele",
   // "Lynda",
   //   "William",
   //   "Thomas"
   // ]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

看上去结果是一样的,其实.pluck就是在.map的基础上进行了封装,而且pluck只能以字符串(String)作为挑选的参数,而map的功能则更加强大 。

用.map包含以及屏蔽属性

别名:_.collect

.map(collection, [iteratee=_.identity], [thisArg]) 
第一个参数是要处理的数组, 
第二个参数是迭代器,该迭代器可以是函数,可以是对象,也可以是字符串

var collection = [
       { first: '赵', last: '子龙', age: 23 },
       { first: '马', last: '超', age: 31 },
       { first: '张', last: '飞', age: 44 },
       { first: '关', last: '羽', age: 38 }
];

//用函数做迭代器
_.map(collection, function(item) {
       return _.pick(item, [ 'first', 'last' ]);
}); 

   // → 
   // [
   //   { first: '赵', last: '子龙'},
   //   { first: '马', last: '超'},
   //   { first: '张', last: '飞' },
   //   { first: '关', last: '羽' }
   // ]

//用对象做迭代器
_.map(collection,{first: '赵'});

//[true,false,false,false]

//用omit去掉指定的属性
_.map(collection, function(item) {
       return _.omit(item, 'first');
});

//[
//  {"last":"子龙","age":23},
//  {"last":"超","age":31},
//  {"last":"飞","age":44},
//  {"last":"羽","age":38}
//]

//用迭代器设置筛选条件
function invalidAge(value, key) {
    return key === 'age' && value < 40;
}

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

//[
//  {"first":"赵","last":"子龙"},
//  {"first":"马","last":"超"},
//  {"first":"张","last":"飞","age":44},
//  {"first":"关","last":"羽"}
//]

猜你喜欢

转载自blog.csdn.net/uncle_long/article/details/80366977