Javascript Array toDictionary(key)

Description

Javascript Array toDictionary(key)


Array.prototype.toDictionary = function(key) {
 if (!key)/*from w w  w. j a va 2 s  . c o  m*/
  key = function(x) { return x.id; };

 var dictionary = {};
 this.forEach(function(item) {
  var currentKey = key(item);
  if (!currentKey)
   return true;
  if (!dictionary[currentKey])
   dictionary[currentKey] = [];
  dictionary[currentKey].push(item);
 });
 return dictionary;
};



PreviousNext

Related