Skip to content

Instantly share code, notes, and snippets.

@kvendrik
Last active August 29, 2015 14:06
Show Gist options
  • Save kvendrik/958bd53743825322dd7d to your computer and use it in GitHub Desktop.
Save kvendrik/958bd53743825322dd7d to your computer and use it in GitHub Desktop.
Test path in object

Instead of this:

if( person !== undefined && person.details !== undefined && person.details.city !== undefined )

Using this method you can use this:

if( person.testPath('details.city') )
Object.prototype.testPath = function(path){
var pieces = path.split('.'),
currPath = this,
passed = true;
pieces.forEach(function(val){
if(currPath[val] === undefined){
passed = false;
} else {
currPath = currPath[val];
}
});
return passed;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment