documentcloud/underscore — pull request #995 by bwiklund (2013-03-04 02:22:02+00:00)
Title: Added a _.createIndex method

This is a function I use a lot, to convert an array into an object keyed off an index. I find it really useful for taking arrays from REST endpoints, and keying them off their id.

Example usage:

var array = [{foo:{bar:'baz'}},{foo:{bar:'boop'}}];
var obj = _.createIndex(array,'foo.bar',true);

result:

{
baz: {foo:{bar:'baz'}},
boop: {foo:{bar:'boop'}}
}

It takes a 'path' as a string, and splits it on ".". It can also take an array in case your parameters have dots in them.

It's third argument is a boolean for whether or not the indexes are unique. If not, it will return an object of arrays of the original elements.