Skip to content

Instantly share code, notes, and snippets.

@rayshan
Created May 14, 2013 19:14
Show Gist options
  • Save rayshan/5578634 to your computer and use it in GitHub Desktop.
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
/**
* 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