Created
June 24, 2016 15:37
-
-
Save pianosnake/d8525fffd1282af66a011842f472d174 to your computer and use it in GitHub Desktop.
Recursive implementation of JavaScript hasOwnProperty().
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
//example: | |
//var nestedObj = {planet: {earth: {'@continent': 'africa'}}}; | |
//hasOwnProperties(nestedObj, 'planet.earth.@continent') //returns true | |
//hasOwnProperties(nestedObj, 'planet.earth.@continent', 'africa') //returns true | |
//hasOwnProperties(nestedObj, 'planet.earth.unicorns') //returns false | |
hasOwnProperties: function(target, path, value){ | |
if (typeof target !== 'object' || target === null) { return false; } | |
var parts = path.split('.'); | |
while(parts.length) { | |
var property = parts.shift(); | |
if (!(target.hasOwnProperty(property))) { | |
return false; | |
} | |
target = target[property]; | |
} | |
if(value){ | |
return target === value; | |
}else{ | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment