Skip to content

Instantly share code, notes, and snippets.

@olaferlandsen
Last active November 17, 2016 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olaferlandsen/d37590fd251553b73ba56fc114dfcf0d to your computer and use it in GitHub Desktop.
Save olaferlandsen/d37590fd251553b73ba56fc114dfcf0d to your computer and use it in GitHub Desktop.
Check if a variable is a object and if path key exists.
/**
* 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