Created
November 19, 2014 14:34
-
-
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
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
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