Created
August 6, 2014 15:51
-
-
Save JessieAMorris/e36ccb6ac07a0e297863 to your computer and use it in GitHub Desktop.
Traverse path for javascript
This file contains hidden or 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
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