var people = [
{firstName : "Thein", city : "ny", qty : 5},
{firstName : "Michael", city : "ny", qty : 3},
{firstName : "Bloom", city : "nj", qty : 10}
];
var results=_.pluck(_.where(people, {city : "ny"}), 'firstName');
For example : I need firstName
and qty
.
To project to multiple properties, you need
map
, not pluck:(Fiddle)
Note that, if you wanted to, you could create a helper method "pluckMany" that does the same thing as pluck with variable arguments:
You can use the
_.mixin
function to add a "pluckMany" function to the_
namespace. Using this you can write simply:(Fiddle)
We don't have to use pluck, omit do the trick as well.
TL;DR Use :
But please read on for explanations as I feel the process of finding this solution is more interesting than the actual answer.
The general pattern would be (it works with
lodash
too) :_.map(array, function(obj) { return _.pick(obj, 'x', 'y', 'z'); });
Given this general
map
function which transforms each element of a collection, there are multiple ways to adapt this to your particular situation (that vouch for the flexibility ofmap
, which is a very basic building block of functional programs).Let me present below several ways to implement our solution :
If you like this way of writing code with
underscore
orlodash
, I highly suggest that you have a look at functional programming, as this style of writing as well as many functions (map
,reduce
amongst many others) come from there.Note : This is apparently a common question in underscore : https://github.com/jashkenas/underscore/issues/1104
This is apparently no accident if these are left out of underscore/lodash : "composability is better than features". You could also say
do one thing and do it well
. This is also why_.mixin
exists.Yep, I wish
pluck
had an option of passing an array, but in the meantime, you could do:YAAUu-Yep Another Answer Using underscore...
My understanding is the author of the question wants to take an array of objects with many properties and strip each object down to a small list of properties.
There are myriad ways of doing so with _ , but I like this way best. Pass in an empty result object which will be "this" inside the function. Iterate with _each , and _pick the fields you want: