Skip to content

Instantly share code, notes, and snippets.

@JessieAMorris
Created August 6, 2014 15:51
Show Gist options
  • Save JessieAMorris/e36ccb6ac07a0e297863 to your computer and use it in GitHub Desktop.
Save JessieAMorris/e36ccb6ac07a0e297863 to your computer and use it in GitHub Desktop.
Traverse path for javascript
var isObject = function isObject(object) {
return Object.prototype.toString.call(object) === "[object Object]";
};
var isArray = function isObject(object) {
return Object.prototype.toString.call(object) === "[object Array]";
};
var dashP = function dashP(path, object) {
var current = object;
var paths = path.split(".");
for(var i = 0; i < paths.length; i++ ) {
var path = paths[i];
if(isObject(current[path])){
current = current[path];
} else {
if(typeof current[path] === "undefined") {
current[path] = {};
current = current[path];
} else {
throw new Error("Path specified was not an object or undefined");
}
}
}
return object;
};
dashP("foo.bar.bazz", {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment