-
-
Save caracal7/24398642892a2adb6d5e7ef82a84cd6a to your computer and use it in GitHub Desktop.
Object Path
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
// 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