Lodash - How to get multiple results

I am using lodash. I like it.

I have an array of users that looks like this:

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

This is how I find the first user and tweak the user property:

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

However, I wanted to wrest the values โ€‹โ€‹of user and age . How can I write this?

+8
javascript lodash
source share
2 answers

If you just want to select the user and age columns from the same result, you can use the pick () function, for example this:

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

If you want to filter and design, you can use where () and map () :

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

If you want the user of the object in the array, and not the user attribute, you can get it from _.find.

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

All Articles