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?
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?
-
1
_.find(users, 'active', false)
will return you an object, You can use it likevar obj = _.find(users, 'active', false);
and then getobj.user
andobj.age
– Satpal Commented May 26, 2015 at 11:14 - 1 What answer do you expect? A new object with user name and age ? – vjdhama Commented May 26, 2015 at 11:16
- 2 Yes, vjdhama new object I want – user4874420 Commented May 26, 2015 at 11:27
- 1 Try this fiddle. – vjdhama Commented May 26, 2015 at 11:37
2 Answers
Reset to default 5If 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}