Last active
August 29, 2015 14:03
-
-
Save codyromano/70eb588b109511d46852 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Search through an array of objects. | |
* | |
* @param {Object} One or more key/value pairs that must exist | |
* in each object for it to be included in the result. | |
* @return {Array} Objects that match the search criteria. | |
*/ | |
Array.prototype.searchObjects = function (params) { | |
if (typeof params !== 'object') { | |
throw new TypeError("Must provide search parameters in object form."); | |
} | |
return this.filter(function (el) { | |
if (typeof el === 'object') { | |
for (var key in params) { | |
if (el[key] && el[key] == params[key]) { | |
return true; | |
} | |
} | |
} | |
return false; | |
}); | |
}; | |
// Example: | |
var rappers = [ | |
{name: "Lil' Wayne", adjective: "Crazy"}, | |
{name: "Big Poppa", adjective: "Hefty"}, | |
{name: "Jay-Z", adjective: "Rich"} | |
]; | |
var result = rappers.searchObjects({adjective: "Hefty"}); | |
// result = {name: "Big Poppa", adjective: "Hefty"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment