简体   繁体   中英

Lodash - How to get multiple results

I am using 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:

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

However, I wanted to pluck the user and the age values. 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:

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

If you want to filter and project then you can use where() and 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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