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

Chantz picture Chantz · May 2, 2012 · Viewed 57.8k times · Source

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.

Answer

cletus picture cletus · Oct 12, 2012

For what it's worth, since underscore.js you can now use _.object()

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