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?
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.
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.
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.
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".
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;
});
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
.
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