Skip to content

Instantly share code, notes, and snippets.

@alanthai
Created February 3, 2015 16:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alanthai/79c305a00b9ba8e18062 to your computer and use it in GitHub Desktop.
Save alanthai/79c305a00b9ba8e18062 to your computer and use it in GitHub Desktop.
Object Path
// Gets value of object given a string path
// Example: objectPathGet({a: {b: {c: {d: "hello"}}}}, "a.b.c.d") // returns "hello"
function objectPathGet(obj, path, _default) {
try {
var keys = path.split(".");
return (function _get(obj) {
var child = obj[keys.shift()];
return keys.length ? _get(child) : child;
})(obj);
} catch(err) {
return _default;
}
}
// Creates paths that don't exist
// Example: var obj = {}
// objectPathSet(obj, "a.b.c", "hello") // => obj = {a: {b: {c: "hello"}}}
function objectPathSet(obj, path, value) {
var keys = path.split(".");
return (function _set(obj) {
var key = keys.shift();
if (keys.length) {
if (typeof obj[key] !== 'object') {
obj[key] = {};
}
_set(obj[key]);
} else {
obj[key] = value;
}
})(obj);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment