Skip to content

Instantly share code, notes, and snippets.

@sshaw sshaw/pick.js
Last active Jun 10, 2017

Embed
What would you like to do?
JavaScript function to pluck truthy properties and functions from an Array of Objects
// https://gist.github.com/sshaw/e21c9a7c82aff15359804e90ea7042a3
// Pluck truthy properties and functions from an Array of Objects
//
// var a = [ {id: 123}, {id: 0}, {id: false}, {id: function() { return 'foo' }} ]
// pick('id', a) returns [123, 'foo']
// var f = pick('id')
// f(a)
var pick = function(property, array) {
var picker = function(_array) {
return _array.reduce(function(acc, v) {
var value = v[property];
if(typeof value === 'function')
value = value();
if(value)
acc.push(value);
return acc;
}, []);
};
return array !== undefined ? picker(array) : picker;
};
export default pick;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.