Skip to content

Instantly share code, notes, and snippets.

@codyromano
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codyromano/70eb588b109511d46852 to your computer and use it in GitHub Desktop.
Save codyromano/70eb588b109511d46852 to your computer and use it in GitHub Desktop.
/**
* 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