LoDash: get an array of values ​​from an array of object properties

I am sure this is somewhere inside the LoDash docs, but I cannot find the right combination.

var users = [{ id: 12, name: Adam },{ id: 14, name: Bob },{ id: 16, name: Charlie },{ id: 18, name: David } ] // how do I get [12, 14, 16, 18] var userIds = _.map(users, _.pick('id')); 
+83
javascript lodash
Feb 05 '15 at 21:49
source share
4 answers

Starting with v4.x you should use _.map :

 _.map(users, 'id'); // [12, 14, 16, 18] 

Thus, this corresponds to the built-in Array.prototype.map method where you should write (ES2015 syntax):

 users.map(user => user.id); // [12, 14, 16, 18] 

Prior to v4.x, you can use _.pluck in the same way:

 _.pluck(users, 'id'); // [12, 14, 16, 18] 
+173
Feb 05 '15 at 21:54
source share

With pure JS:

 var userIds = users.map( function(obj) { return obj.id; } ); 
+11
Feb 05 '15 at 22:00
source share

Lodash v4.0.0 _.pluck removed in favor of _.map in new release

Then you can use this:

 _.map(users, 'id'); // [12, 14, 16, 18] 

You can see in github changelog

+10
Jan 21 '16 at 16:04
source share

This will give you what you want in the popup.

 for(var i = 0; i < users.Count; i++){ alert(users[i].id); } 
-8
Feb 05 '15 at 21:58
source share



All Articles