TL;DR Just use :
var results = _.chain(people)
.where({ city: "ny" })
.map(_.partialRight(_.pick, 'firstName', 'qty'))
.value();
However, it's worth reading further for the explanations as the process of discovering this solution is more intriguing than the answer itself.
The basic structure would be (also applicable with lodash
) :
_.map(array, function(obj) { return _.pick(obj, 'x', 'y', 'z'); });
Given this fundamental map
function that transforms each element of a collection, there are various ways to customize it to your specific case (showcasing the versatility of map
, essential in functional programming).
Below are several approaches to implement our solution :
var _ = require('lodash'); // @lodash 2.4.1 at the time of writing
// Use underscore if preferred, but refer to http://stackoverflow.com/questions/13789618/differences-between-lodash-and-underscore
/* Data */
var people = [{
firstName: "Thein",
city: "ny",
qty: 5
}, {
firstName: "Michael",
city: "ny",
qty: 3
}, {
firstName: "Bloom",
city: "nj",
qty: 10
}];
...
console.log(results);
If you appreciate coding with underscore
or lodash
, exploring functional programming is highly recommended, since this style and many functions (map
, reduce
among others) originate from there.
Note: This seems to be a common query in the realm of underscore:
https://github.com/jashkenas/underscore/issues/1104
It appears intentional that these functionalities are not included in underscore/lodash: "composability surpasses features". One could also say do one thing and do it well
. Hence, the existence of _.mixin
.