Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 516
Chantz Avatar asked May 02 '12 15:05

Chantz


People also ask

How do you use underscore in JavaScript?

Adding Underscore to a Node. Once added, underscore can be referred in any of the Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.

What is _ each in JavaScript?

The _.each function accepts an array or an object, an iteratee function and an optional context object, the iteratee function is invoked once and in order for each array item The iteratee function provides 3 arguments item - The current iterated object (or value if an object was passed) i - The index of the iterated ...

Can JavaScript map have object as key?

Introduction to JavaScript Map object An object always has a default key like the prototype. A key of an object must be a string or a symbol, you cannot use an object as a key. An object does not have a property that represents the size of the map.

Is underscore js still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.


2 Answers

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] })); 
like image 141
cletus Avatar answered Oct 10 '22 12:10

cletus


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'); 
like image 43
user3699395 Avatar answered Oct 10 '22 10:10

user3699395