Underscore utility method _.snatch

like _.pluck but works for both methods and properties.

by ckniffen

HTML

<script src="https://raw.github.com/documentcloud/underscore/master/underscore.js"></script>

JavaScript

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

_.snatch = function(obj, key) {
    return _.map(obj, function(value) {
        return _.result(value, key);
    });
};

var test = [
    {
    'something': 'yay',
    'morestuff': 'ok'},
{
    'something': function() {
        return 'hello'
    },
    'morestuff': 'okay'}
];

console.log(_.snatch(test, 'something'));
console.log(_.snatch(test, 'morestuff'));

$('body').append(_.snatch(test, 'something').join(', ') + '<br>');
$('body').append(_.snatch(test, 'morestuff').join(', ') + '<br>');