Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  143] [ 5]  / answers: 1 / hits: 37512  / 11 Years ago, tue, august 13, 2013, 12:00:00

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;
}

More From » object

 Answers
4

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


[#76372] Monday, August 12, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alli

Total Points: 409
Total Questions: 101
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
alli questions
Sat, Apr 23, 22, 00:00, 2 Years ago
Mon, May 18, 20, 00:00, 4 Years ago
Tue, Mar 24, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;