Beautiful JS

JavaScript that belies the common conception of beauty

Underscore's pluck

Underscore has taken a common use-case of the conventional map method and made it a method of its own, pluck:

_.pluck = function(obj, key) {
  return _.map(obj, function(value){ return value[key]; });
};

It takes an array or object and plucks values out of its members:

var a = document.getElementsByTagName('a');
_.pluck(a, 'href'); // get all `href` attributes as an array

It’s dead simple, but proves how valuable it is to abstract based on common usage.

PS. Please check out the new jsapi.info, a site I created to explore the source of various libraries, via which I discovered pluck!

Posted by James on 02 Nov 2011 | linky

Subscribe or follow @Beautiful_JS! | Fork then send a pull request to contribute.

Disclaimer: Beautiful code is readable, maintainable and scalable. It's not just nice to look it.