Created
May 14, 2013 19:14
-
-
Save rayshan/5578634 to your computer and use it in GitHub Desktop.
Javascript function to loop through flattened array and return whole object or value to specified key
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
/** | |
* loop through flattened array and return whole object or value to specified key | |
* e.g. array: [{"idKey": 1, "otherKey": "hello"}, | |
* {"idKey": 2, "otherKey": "world"}] | |
* @param arr | |
* @param key search for this key | |
* @param value match searched key's value to desired value | |
* @param {string=} keyToReturn return value of this key | |
* @returns {*} | |
*/ | |
function arrGet (arr, key, value, keyToReturn) { | |
var result = {}; | |
for (var i = 0; i < arr.length; i++) { | |
if (arr[i][key] === value) { | |
result = arr[i]; | |
break; | |
} | |
} | |
return keyToReturn ? result[keyToReturn] : result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment