Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an object from _.pluck with lo-dash/underscore

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?

like image 299
JJJollyjim Avatar asked Sep 05 '13 09:09

JJJollyjim


People also ask

What is _ each?

each _.each(list, iteratee, [context]) Alias: forEach source. Iterates over a list of elements, yielding each in turn to an iteratee function. The iteratee is bound to the context object, if one is passed.

How do you pluck in JavaScript?

pluck() function is used when we need to extract a list of a given property. Like we have to find out the name of all the students, then we can simply apply the _. pluck() function on the details of all the students. It will only extract the name from the details of all the stuf=dents and display it.

What is underscore js used for?

Underscore. js is a utility library that is widely used to deal with arrays, collections and objects in JavaScript. It can be used in both frontend and backend based JavaScript applications. Usages of this library include filtering from array, mapping objects, extending objects, operating with functions and more.

What is underscore variable in JavaScript?

It is simply the convention of prepending an underscore ( _ ) to a variable name. This is done to indicate that a variable is private and should not be toyed with. For example, a "private" variable that stores sensitive information, such as a password, will be named _password to explicitly state that it is "private".


2 Answers

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;
});
like image 118
John-David Dalton Avatar answered Sep 21 '22 11:09

John-David Dalton


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.

like image 31
TWiStErRob Avatar answered Sep 18 '22 11:09

TWiStErRob