我们写处理业务时候经常要处理一些基本类型的复杂处理,为此我们会增加很多不惜要的代码,是有时候还需要你定义多余的变量, lodash是个很好用的工具类,也是不少框架的依赖插件举两个我用过的例子
数组
every检查数组对象属性的一致性
orderBy
和 sortby 都用于排序
filter过滤
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false }
];
_.filter(users, function(o) { return !o.active; });
// => objects for ['fred']
// The `_.matches` iteratee shorthand.
_.filter(users, { 'age': 36, 'active': true });
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.filter(users, ['active', false]);
// => objects for ['fred']
// The `_.property` iteratee shorthand.
_.filter(users, 'active');
// => objects for ['barney']
对象
筛选部分键值对,返回新的对象
var object = { 'a': 1, 'b': '2', 'c': 3 };
_.pick(object, ['a', 'c']);
// => { 'a': 1, 'c': 3 }
忽略部分键值对, 返回新的对象
var object = { 'a': 1, 'b': '2', 'c': 3 };
_.omit(object, ['a', 'c']);
// => { 'b': '2' }
网友评论