Question

I'm trying to convert

var stuff = { 1234: [{ name: "obj1" }], 3456: [{ name: "obj2" }] };

to

{ 1234: { name: "obj1" }, 3456: { name: "obj2" } }

(notice the singular arrays).

I figured out that:

_.mapValues(stuff, function(arr) { return _.first(arr); })

does the job, but what I don't understand why isn't the following enough?

_.mapValues(stuff, _.first)

It returns

{ 1234: [], 3456: [] }
Was it helpful?

Solution

_.mapValues is passing more than just one argument to callback function. So your first example (to be equivalent) to second one should be:

_.mapValues(stuff, function() { return _.first.apply(this, arguments)})

As you can see here arguments passed to callback function are keyValue, keyName, stuff object.

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