Last active
December 21, 2015 15:09
-
-
Save cskevint/6324739 to your computer and use it in GitHub Desktop.
_.pluckNested is a better implementation of _.pluck from underscore.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Convenience version of a common use case of `map`: fetching a property. | |
// The property can be nested using "." notation. | |
// _.pluckNested([{a:{z:1}},{a:{z:2}}],"a.z") ==> [1, 2] | |
_.pluckNested = function(obj, key) { | |
var objKey = key.split('.'); | |
return _.map(obj, function(o) { | |
var value = o, item; | |
_.each(objKey, function(key) { | |
if(_.isObject(value[key])) { | |
value = value[key]; | |
} else { | |
item = value[key]; | |
} | |
}); | |
return item; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment