Skip to content

Instantly share code, notes, and snippets.

@liamness
Created November 19, 2014 14:34
Show Gist options
  • Save liamness/bde065b2290405663a40 to your computer and use it in GitHub Desktop.
Save liamness/bde065b2290405663a40 to your computer and use it in GitHub Desktop.
Traverses an object to any depth to find and return an object with a property of a given value
var findInObj = function(obj, property, value) {
var currentObj, result;
var check = function(obj, property, value) {
if(obj[property] === value) {
return obj;
} else if(typeof obj === 'object') {
var childObj = findInObj(obj, property, value);
return childObj;
}
return false;
};
if(obj instanceof Array) {
for(var i = 0, len = obj.length; i < len; i++) {
currentObj = obj[i];
result = check(currentObj, property, value);
if(result !== false) {
return result;
}
}
} else {
for(var prop in obj) {
if(obj.hasOwnProperty(prop)) {
currentObj = obj[prop];
} else {
continue;
}
result = check(currentObj, property, value);
if(result !== false) {
return result;
}
}
}
return false;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment