Last active
November 17, 2016 17:40
-
-
Save olaferlandsen/d37590fd251553b73ba56fc114dfcf0d to your computer and use it in GitHub Desktop.
Check if a variable is a object and if path key exists.
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
/** | |
* Implementation with pure javascript | |
* | |
* Example: | |
* | |
* var someObject = {a: {b: {c: 1}}}; | |
* | |
* objectPathExists(someObject, 'a'); // return true | |
* objectPathExists(someObject, 'a.b'); // return true | |
* objectPathExists(someObject, 'a.b.c'); // return true | |
* objectPathExists(someObject, 'a.b.c.e'); // return false | |
*/ | |
function objectPathExists (_ob, _path) { | |
if (_ob === null || _ob === undefined) return false; | |
_path = _path.split('.'); | |
var count = _path.length, _object = _ob; | |
for (var i = 0; i < count; i++) { | |
if (Object.keys(_object).length >= 0 && _object.constructor === Object) { | |
if ( _object.hasOwnProperty(_path[i]) ) { | |
_object = _object[_path[i]] | |
if (count-1 == i) return true; | |
} | |
} | |
} | |
return false; | |
} | |
/** | |
* Implementation for prototype | |
* | |
* Example: | |
* | |
* var someObject = {a: {b: {c: 1}}}; | |
* | |
* someObject.pathExists('a'); // return true | |
* someObject.pathExists('a.b'); // return true | |
* someObject.pathExists('a.b.c'); // return true | |
* someObject.pathExists('a.b.c.d'); // return false | |
*/ | |
Object.prototype.pathExists = function (path) { | |
return objectKeyExists(this, path); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment