I needed a bit of JavaScript that would look at an array of objects and see if it contained an element that matched a certain criteria. I’m sure that this is online somewhere, but I couldn’t turn it up. There are lots of examples for finding if an array contains a certain specific element, but that wasn’t what I needed. In my case I wanted to pick out the object from an array that had ‘type’ property equal to a certain string.
Since I find so many great examples online I wanted to give somthing back to the community in the hope that this will save someone time and effort down the line.
I’m a long time out from my last formal class in programming languages so if this type of search has a particular name, please let me know!
<script language="JavaScript">
/* search all elements in an array for one that has a property key equal to value */ Array.prototype.deepContains = function (key,value) { var i = this.length; var compareFunc = function(x) { return x[key] == value; }; while (i--) { if (compareFunc (this[i])) { return true; } } return false; } /* build an array for testing */ var arr = new Array(); var obj = new Object(); obj['id'] = 22; arr[0] = obj; obj = new Object(); obj['id'] = 54; arr[1] = obj; obj = new Object(); obj['id'] = 77; arr[2] = obj; /* usage example */ alert (arr.deepContains( 'id', 1 ) ); // false, no Object has 'id' = 1 alert (arr.deepContains( 'id', 54 ) ); // Object with 'id' = 54 </script>