What is the object equivalent of _.pluck

Brad Dwyer picture Brad Dwyer · Aug 13, 2013 · Viewed 31.4k times · Source

I've re-implemented my own version of what I need but I suspect this is already included in underscore since it's so simple and so closely related to many other functions. But I can't think of what it should be called.

Basically, what I want is a version of _.pluck that works with objects and returns an object instead of an array (with its associated keys).

So, for instance, if I had an object like this:

elements: {
    steam: {
        temperature: 100,
        color: 'orange',
        state: 'gas'
    },
    water: {
        temperature: 50,
        color: 'blue',
        state: 'liquid'
    },
    ice: {
        temperature: 0,
        color: 'white',
        state: 'solid'
    }
}

I'd want to call _.something(elements, 'temperature')

And have it return

{
    steam: 100,
    water: 50,
    ice: 0
}

Instead of _.pluck(elements, 'temperature') which returns

[100, 50, 0]

What is this transformation called and is it already included in underscore? I've written a quick version myself with jQuery's each loop since I'm more familiar with jQuery than underscore (included below) but would prefer to use one from the library if possible.

$.objPluck = function(obj, key) {
    var ret = {};
    $.each(obj, function(k, value) {
        ret[k] = value[key];
    });
    return ret;
}

Answer

Mathletics picture Mathletics · Aug 13, 2013

There's no method to do exactly this in underscore 1.4.4, but if you want to stay in underscore, you can do

_.object(_.keys(elements), _.pluck(elements, 'temperature'))

Demo at jsfiddle courtesy of bfavaretto


As of underscore 1.8.3, this can be done succinctly with _.mapObject(elements, 'temperature');.

Updated demo