Created
March 27, 2014 11:49
-
-
Save detj/9805818 to your computer and use it in GitHub Desktop.
Search an object inside an Array of objects using a key
This file contains hidden or 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
/** | |
* 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