Reputation:
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?
Upvotes: 9
Views: 11560
Reputation: 1935
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 } ]
Upvotes: 5
Reputation: 84
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}
Upvotes: 1