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

Javascriptunderscore.jsJavascript Objects

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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');

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

for ES6, it's

var some_map = _.chain(some_object_array)
                .map(item => [item.id, item])
                .object()
                .value()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChantzView Question on Stackoverflow
Solution 1 - JavascriptcletusView Answer on Stackoverflow
Solution 2 - Javascriptuser3699395View Answer on Stackoverflow
Solution 3 - JavascriptOtto AllmendingerView Answer on Stackoverflow
Solution 4 - JavascriptMarwane K.A.View Answer on Stackoverflow
Solution 5 - JavascriptAA.View Answer on Stackoverflow
Solution 6 - JavascriptryanView Answer on Stackoverflow