user4874420
user4874420

Reputation:

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?

Upvotes: 9

Views: 11560

Answers (2)

Will Smith
Will Smith

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

xavier hans
xavier hans

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

Related Questions