Skip to content

Loading…

_.pluck extended to support fetching multiple properties #1113

Closed
wants to merge 1 commit into from

4 participants

@vilius

This seems like an intuitive functionality. Example:

var people = [{first : 'moe', last: 'doe', age : 30}, {first : 'curly', last: 'brackets', age : 50}];
_.pluck(people, 'first'); // returns ['moe', 'curly']
_.pluck(people, ['first', 'last']); // returns [ ['moe', 'doe'], ['curly', 'brackets'] ]

Performance impact: 20% slower

@braddunbar
Collaborator

Mornin' @vilius, thanks for the patch! However, this one has already been discussed several times (#1104, #48, #469, #1070). I see the usefulness of such an enhancement, but I think it's best for underscore to encourage composition over specialization in cases like this. This can already be described fairly concisely by composing _.zip and _.pluck.

_.zip(_.pluck(people, 'first'), _.pluck(people, 'last'));
@braddunbar braddunbar closed this
@dandv

I've read the entire underscorejs documentation and _.zip composed with _.pluck just hasn't occurred to me. The repeated requests for plucking multiple keys suggest this is simply a demanded feature. The human mind happens to work less mathematically than some (including myself) would like.

@akre54
Collaborator

Underscore is great in that it has a small number of powerful higher-order function building blocks that you can use to build anything more complicated yourself. It's not going to cover every single feature and use case you'd like to have in the library, but you should feel free to mixin this pluckKeys function if you need it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on May 13, 2013
  1. @vilius
This page is out of date. Refresh to see the latest.
Showing with 8 additions and 3 deletions.
  1. +1 −0 test/collections.js
  2. +7 −3 underscore.js
View
1 test/collections.js
@@ -251,6 +251,7 @@ $(document).ready(function() {
test('pluck', function() {
var people = [{name : 'moe', age : 30}, {name : 'curly', age : 50}];
equal(_.pluck(people, 'name').join(', '), 'moe, curly', 'pulls names out of objects');
+ equal(_.pluck(people, ['name', 'age']).join(' '), 'moe,30 curly,50', 'allow key argument to be an array');
});
test('where', function() {
View
10 underscore.js
@@ -232,9 +232,13 @@
});
};
- // Convenience version of a common use case of `map`: fetching a property.
- _.pluck = function(obj, key) {
- return _.map(obj, function(value){ return value[key]; });
+ // Convenience version of a common use case of `map`: fetching a single or multiple properties.
+ _.pluck = function(obj, keys) {
+ return _.map(obj, function(value) {
+ return !_.isArray(keys) ? value[keys] : _.map(keys, function(key) {
+ return value[key];
+ });
+ });
};
// Convenience version of a common use case of `filter`: selecting only objects
Something went wrong with that request. Please try again.