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;
}
The _. pluck() function is used when we need to extract a list of a given property.
js collection pluck method is used to retrieve an attribute from each model in the collection. It is equivalent to calling map and returning a single attribute from the iterator.
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
Worth adding in here a solution that uses ES6 arrow functions, etc:
Object.keys(elements).map(f=>elements[f].temperature)
Note that this won't work on older javascript engines, but in node.js 0.12 with --harmony
it works great, or with node.js 4.x and later as well. I just tested this in Chrome 46 and it works fine.
It has the advantage of not needing any extra libraries such as underscore or lodash, but of course only works on new JS engines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With