Skip to content

Instantly share code, notes, and snippets.

@detj
Created March 27, 2014 11:49
Show Gist options
  • Save detj/9805818 to your computer and use it in GitHub Desktop.
Save detj/9805818 to your computer and use it in GitHub Desktop.
Search an object inside an Array of objects using a key
/**
* Searches object in Array by key
*
* Usage:
*
* List should be an Array like this
* var foo = {};
* var list = [
* { name: {} }, { name: foo }, { name: {} }
* ];
*
* contains('name', foo, list); // Returns 1
* contains('name', {}, list); // Returns -1
*
*
* Return the index if object is found, else -1
*
* @param {String} key
* @param {Object} obj
* @param {Array} list
* @returns {Number}
*/
function contains(key, obj, list) {
for (var i = 0, len = list.length; i < len; i += 1) {
if (list[i][key] === obj) return i;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment