Skip to content

Instantly share code, notes, and snippets.

@orvigas
Last active April 29, 2018 15:33
Show Gist options
  • Save orvigas/ed795f5d8c5a8ed2cf32cd5cd4e896f7 to your computer and use it in GitHub Desktop.
Save orvigas/ed795f5d8c5a8ed2cf32cd5cd4e896f7 to your computer and use it in GitHub Desktop.
Function to look for a key inside a complex object in Javascript
/**
* This function allows to search a especific key in a complex object
* @author orvigas@gmail.com
* @param (Object) o: Object in which you look for the key
* @param (string) key: Name of key you're looking for
* @return (mixed) $r: Return object or value related with key name,
* instead if key were not found it return undefined
*/
function hasKey(o, key) {
var $r = void 0;
Object.keys(o).some(function (k) {
if (k === key) {
$r = o[k];
return true;
}
if (o[k] && typeof o[k] === 'object') {
$r = hasKey(o[k], key);
return $r !== undefined;
}
});
return $r;
}
/**Example**/
var obj = {
"prop1": {
"sprop11": true,
"sprop12": null
},
"prop2": [
{
"sprop21": 28,
"sprop22": [
{
"sprop221": 28,
"inner222": [
{
"stage_id": 28,
}
, {
"deepest": "deepest property"
}]
}]
}]
};
/** key:prop1 **/
console.log(hasKey(obj, 'prop1'));
/** Output: {"sprop11":true,"sprop12":null} **/
/** key:stage_id **/
console.log(hasKey(obj, 'stage_id'));
/** Output: 28 **/
/** key:deepest **/
console.log(hasKey(obj, 'deepest'));
/** Output: deepest property **/
/** key:non-existent **/
console.log(hasKey(obj, 'non-existent'));
/** Output: undefined **/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment