简体   繁体   English

Lodash - 如何获得多个结果

[英]Lodash - How to get multiple results

I am using lodash. 我正在使用lodash。 I like it. 我喜欢。

I have a users array which looks like this: 我有一个用户数组,如下所示:

var users = [{
    'user': 'barney',
    'age': 36,
    'active': true
}, {
    'user': 'fred',
    'age': 40,
    'active': false
}, {
    'user': 'pebbles',
    'age': 1,
    'active': true
}];

Here's how I'm finding the first user and plucking the user property: 以下是我找到第一个用户并获取user属性的方法:

_.result(_.find(users, 'active', false), 'user');
// 'fred'

However, I wanted to pluck the user and the age values. 但是,我想要提取userage值。 How can I write this? 我怎么写这个?

If you just want to select the user and age columns from a single result you can use the pick() function like this: 如果您只想从单个结果中选择userage列,可以使用pick()函数,如下所示:

_.pick(_.find(users, 'active'), ['user', 'age']);
// 'barney', 36

If you want to filter and project then you can use where() and map() : 如果你想过滤和项目,那么你可以使用where()map()

_.map(_.where(users, 'active'), _.partialRight(_.pick, ['user', 'age']));
// [{ name: 'barney', age: 36 }, { user: 'pebbles', age: 1 } ]

If you want the object user in the array and not the attribute 'user', you can get it from _.find. 如果你想要数组中的对象用户而不是属性'user',你可以从_.find获取它。

_.find(users, 'active', false);
// {'user': 'fred', 'age': 40, 'active': false}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM