Getting object from _.pluck with lo-dash / underline

I have an object structured as follows:

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

However, I would like the object to be structured as follows:

 { first_item: 4, second_item: 6, } 

I would expect to get this result using _.pluck :

 _.pluck(my_object, "important_number") 

But it gives me:

 [0: 4, 1: 6] 

Ok, but I need the actual names of the objects. I messed 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 not as simple as we would like. Is there a better solution in underscore / lodash, or is it the best it will get?

+6
source share
3 answers

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

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

In fact, what you are describing, that is, " pluck for object values", can be written as:

 _.mapValues(my_object, "important_number") 

See the documentation for _.mapValues .

_.createCallback - which uses a string for the magic property - is used throughout Lo-Dash: search for "_.pluck" style callback .

+5
source

I really like to use Lo-Dash / Underscore, but if you need to use 2 functions instead of the usual loop, you better use the "old_school" 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; } 

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

Normal for a loop is at least 2x faster than any other method that you guys posted here. And this is mainly because it only walks around the object once.

+3
source

Source: https://habr.com/ru/post/953227/


All Articles