Skip to content

Instantly share code, notes, and snippets.

@pianosnake
Created June 24, 2016 15:37
Show Gist options
  • Save pianosnake/d8525fffd1282af66a011842f472d174 to your computer and use it in GitHub Desktop.
Save pianosnake/d8525fffd1282af66a011842f472d174 to your computer and use it in GitHub Desktop.
Recursive implementation of JavaScript hasOwnProperty().
//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