Posted By

Pjotor on 08/12/14


Tagged

array json traverse


Versions (?)

getItemByKey


 / Published in: JavaScript
 

URL: http://pjotor.com

Returns the (first) object matching key/val if found.

  1. //As function
  2.  
  3. function getItemByKey(key, val, container){ //Returns the object found or false
  4. //jQuery grep function
  5. var grep = function (a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e};
  6. //jQuery map function
  7. var map = function (a,b,c){var d,f=0,g=a.length,i=[];for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);return [].concat.apply([],i)};
  8.  
  9. //Key matching function
  10. var matchKey = function(o){ return o[key] === val ? o : false; }
  11.  
  12. //Reduce function
  13. var filterContainer = function(b){ return b; };
  14.  
  15. var obj = grep(map( container, matchKey ), filterContainer );
  16.  
  17. //Only return the first instance of the match on the key/value pair
  18. return obj.length? obj[0] : false;
  19. }
  20.  
  21. //As prototype
  22.  
  23. Object.prototype.byKeyVal = function(key, val){ //Returns the object found or false
  24. var container = this;
  25.  
  26. //jQuery grep function
  27. var grep = function (a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e};
  28. //jQuery map function
  29. var map = function (a,b,c){var d,f=0,g=a.length,i=[];for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);return [].concat.apply([],i)};
  30.  
  31. //Key matching function
  32. var matchKey = function(o){ return o[key] === val ? o : false; }
  33.  
  34. //Reduce function
  35. var filterContainer = function(b){ return b; };
  36.  
  37. var obj = grep(map( container, matchKey ), filterContainer );
  38.  
  39. //Only return the first instance of the match on the key/value pair
  40. return obj.length? obj[0] : false;
  41. }

Report this snippet  

You need to login to post a comment.