Is there a lodash function where you can create a collection from an other one by picking only specified attributes?
stats = [{a:1, b:1}, {a:2, b:2}]
reducedStats = _.pick(stats, 'a'); // now is [{a:1},{a:2}]
The normal pick
only works for objects, not for collections.
I achieved it with
stats = stats.map(_.partialRight(_.pick, 'a'));
which is somewhat verbose.
The _. pick() method is used to return a copy of the object that is composed of the picked object properties. Syntax: _.pick( object, paths )
each. The _each method does exactly what it sounds like. It works on collections (arrays or objects), and will iterate over each element in the collection invoking the function you specified with 3 arguments (value, index, list) with index being replaced by key if used on an object.
Because Lodash is updated more frequently than Underscore. js, a lodash underscore build is provided to ensure compatibility with the latest stable version of Underscore.
In my example here, I add a method called make
that does your task.
var _ = require('lodash');
_.make = (arr, ...args) => arr.map(obj => _.pick(obj, args));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With