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

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]
}));

for your case, you should use the indexBy function:

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

var some_grouped_map = _.indexBy(some_object_array, 'id');

There is also this method

_.reduce(data, function (o, item) { o[item.key] = item.value; return o }, {})

Which is one statement with two statements in the inner function.


I don't think there's something closer than groupBy for your needs. Even if there was, it wouldn't do better than a simple:

var some_map = {};
_.each(some_object_array, function(val) {
  some_map[val.id] = val;
});

I this case you don't need to iterate the array. Not map, not reduce, not transform. All you need is the old pluck

_.object(_.pluck(some_object_array, 'id'), some_object_array);