Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equivalent of _.pick() but for array in Lo-dash

I have the following collection:

var columns = [     { key:'url', width:20, type:'text' },     { key:'title', width:21, type:'text' },     { key:'desc', width:22, type:'text' },     { key:'domain', width:23, type:'text' },     { key:'user', width:24, type:'text' } ]; 

I'm looking for a method to map an array of objects with picked keys, something along the lines of:

_.mapPick(columns, [width])  // [{width:20},{width:21},{width:22},{width:23},{width:24}] 

I know I can extend lo-dash like this:

_.mixin({     mapPick:  mapPick:function (objs,keys){         return _.map(objs, function (obj) {             return _.pick(obj,keys)         })     }  }); 

I'm not sure if there is some native function that I'm missing.

I found a similar question here but I'm looking for a more lo-dash native way.

like image 613
pery mimon Avatar asked May 26 '15 16:05

pery mimon


People also ask

What is _ get?

Overview. The _. get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.

Is array equal Lodash?

The Lodash _. isEqual() Method performs a deep comparison between two values to determine if they are equivalent. This method supports comparing arrays, array buffers, boolean, date objects, maps, numbers, objects, regex, sets, strings, symbols, and typed arrays.

What does pick from Lodash do?

Lodash helps in working with arrays, strings, objects, numbers, etc. The _. pick() method is used to return a copy of the object that is composed of the picked object properties.

How do I get the last element of an array using Lodash?

last() method is used to get the last element of the array i.e. (n-1)th element. Parameters: This function accepts single parameter i.e. the array. Return Value: It returns the last element of the array.


1 Answers

I think the map() + pick() approach is your best bet. You could compose the callback instead of creating an inline function however:

_.map(columns, _.partialRight(_.pick, 'key')); 
like image 198
Adam Boduch Avatar answered Oct 14 '22 09:10

Adam Boduch