Question

I have an object structured like this:

var my_object = {
  first_item: {important_number: 4},
  second_item: {important_number: 6},
}

However, I would like an object structured like this:

{
  first_item: 4,
  second_item: 6,
}

I would have expected to be able to get this result with _.pluck:

_.pluck(my_object, "important_number")

But this gives me:

[0: 4, 1: 6]

Good, but I need the actual names of the objects. I fiddled around and ended up with this:

_.reduce(my_object, function(memo, val, key) {
  memo[key] = val.content;
  return memo;
}, {});

Which has the desired effect, but isn't as simple as I would like. Is there a better solution in underscore/lodash, or is this the best it will get?

Was it helpful?

Solution

In Lo-Dash you could also use _.transform, a more powerful alternative to _.reduce:

_.transform(my_object, function(memo, val, key) {
  memo[key] = val.important_number;
});

OTHER TIPS

Actually what you're describing - that is "pluck for object values" - can be written as:

_.mapValues(my_object, "important_number")

See documentation of _.mapValues.

_.createCallback - which does the string to property magic - is used all over the place in Lo-Dash: search for "_.pluck" style callback.

I know it's fun to use Lo-Dash/Underscore, but if you have to use 2 functions instead of just using a regular loop, you're better off using 'old_school' coding style:

var data = {
  first_item: {important_number: 4},
  second_item: {important_number: 6},
};

var obj = {};

for (var i in data) {
  if (data.hasOwnProperty(i)) obj[i] = data[i].important_number;  
}

Just to prove my point, I updated your JsPerf to include the regular for loop, and watch the magic: http://jsperf.com/getting-an-object-from-pluck/2

Regular For Loop is at least 2x faster than any other method you guys posted here. And that's mainly because it only traverses the object once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top