JavaScript ToDictionary

Anyone familiar with Linq's ToDictionary method may be looking for a similar technique in JavaScript.

The cool thing about JavaScript is that first-order properties (properties attached to the first prototype of the instance) are usually implemented in a "dicationary-like" way. Thus we can use properties to achieve fast lookups.

The task is, given an array of objects, create an O(1) object lookup based on some key.

var data = [  
  { id: 1, name: 'Brian'},
  { id: 2, name: 'Jake'},
  { id: 3, name: 'Tim'}
];

// Convert to

var lookup = {  
  '1': { id: 1, name: 'Brian' },
  '2': { id: 2, name: 'Jake' },
  '3': { id: 3, name: 'Tim' }
};

The POJO approach would be to do something like:

var lookup = {};  
data.forEach(function(datum) {  
  lookup[datum.id] = datum;
});

Alternatively, using Underscore, you can create an object lookup by using _.indexBy.

// by property
_.indexBy(data, 'id');

// by iterator function
_.indexBy(data, function(datum) {  
  return datum.id; 
});
comments powered by Disqus