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

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.


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

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

Need Your Help

Powershell to compare output with a CSV file?

powershell csv comparison

I am using the code below to get a list of computer names where they were last modified 181 days ago. I have a .csv file with 2 columns (ComputerName, UserName) Is there a way I can match the outpu...

PHP SFTP/SSH transfer

php ssh sftp transfer

I posted a question a little while ago but I asked about FTP, which is the wrong question (doh!). I need to automatically transfer images (e.g. test.jpg) from one server to another using SFTP/SSH.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.