YarGnawh YarGnawh - 4 months ago 17
Javascript Question

LoDash: Get an array of values from an array of object properties

I'm sure it's somewhere inside the LoDash docs, but I can't seem to 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'));

Answer

For lodash version before 4.x you need to use _.pluck:

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

Since v4.x you should use _.map instead:

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

this way it is corresponds to native Array.prototype.map method where you would write (ES2015 syntax):

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