Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_.pick for collections (underscore/lodash)

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.

like image 672
Stephan Hoyer Avatar asked Apr 11 '14 13:04

Stephan Hoyer


People also ask

What is _ pick?

The _. pick() method is used to return a copy of the object that is composed of the picked object properties. Syntax: _.pick( object, paths )

What does _ each do?

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.

Why is lodash underscore?

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.


1 Answers

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));
like image 160
Matt Avatar answered Sep 29 '22 13:09

Matt