lodash 常用方法

您所在的位置:网站首页 pluck记忆方法 lodash 常用方法

lodash 常用方法

2024-01-27 20:07| 来源: 网络整理| 查看: 265

挑选数据 .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 ] 123456789

其实我们也可以用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" // ] 123456789101112131415

看上去结果是一样的,其实.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":"羽"} //]


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3