Underscore.js: create a map out of list of objects using a key found in the object

I am using the excellent Underscore.js library. I have a specific task which I can do fine using JavaScript or jQuery but was wondering if there was some sort of abstraction avaialable in Underscore that I was missing out on.

Essentially I have an object like so -

var some_object_array = [{id: "a", val: 55}, {id: "b", val: 1}, {id: "c", val: 45}];

I want to convert this into -

var some_map = {"a": {id: "a", val: 55}, "b": {id: "b", val: 1}, "c": {id: "c", val: 45}};

I know that I can use _.groupBy(some_object_array, "id"). But this returns a map like so -

var some_grouped_map = {"a": [{id: "a", val: 55}], "b": [{id: "b", val: 1}], "c": [{id: "c", val: 45}]};

Note that this does what it is advertised to do. But I was hoping to get some_map without iterating over the objects myself.

Any help appreciated.

Answers


FWIW since underscore.js you can now use _.object()

var some_map = _.object(_.map(some_object_array, function(item) {
   return [item.id, item]
}));

Need Your Help

shorthand switch statement with conditional OR operator

javascript jquery

Is it possible to do that? For exanple for 'a' or 'b' is equal to 'X'. If 'c' or 'd' or 'e' is equal to 'Y'

When I search listview item and then click desire item, it does open first position of List View

java android listview

I have Searchable country ListView. When I click Country List Item without search, it's works properly. but when I type Brazil in search box and click Brazil, then open Country_Details.Java Activit...