Last active
February 22, 2019 14:36
-
-
Save victornpb/4c7882c1b9d36292308e to your computer and use it in GitHub Desktop.
access a object value using a path like getDeepVal(obj, "foo.bar.baz")
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
/** | |
* Access a deep value inside an object | |
* Works by passing a path like "foo.bar", also works with nested arrays like "foo[0][1].baz" | |
* @author Victor B. https://gist.github.com/victornpb/4c7882c1b9d36292308e | |
* Unit tests: http://jsfiddle.net/Victornpb/0u1qygrh/ | |
* @param {any} object Any object | |
* @param {string} path Property path to access e.g.: "foo.bar[0].baz.1.a.b" | |
* @param {any} [defaultValue=undefined] Optional value to return when property doesn't exist or is undefined | |
* @return {any} | |
*/ | |
function getDeepVal(object, path, defaultValue=undefined) { | |
if (typeof object === 'undefined' || object === null) return defaultValue; | |
const pathArray = path.split(/\.|\[["']?|["']?\]/); | |
for (let i = 0, l = pathArray.length; i < l; i++) { | |
if (pathArray[i] === '') continue; | |
object = object[pathArray[i]]; | |
if (typeof object === 'undefined' || object === null) return defaultValue; | |
} | |
return (typeof object === 'undefined' || object === null) ? defaultValue : object; | |
} |
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
/** | |
* Set a deep property on nested objects | |
* @param {object} obj A object | |
* @param {String} path A path | |
* @param {Any} val Anything that can be set | |
* @author Victor B. https://gist.github.com/victornpb/4c7882c1b9d36292308e | |
*/ | |
function setDeepVal(obj, path, val) { | |
var props = path.split('.'); | |
for (var i = 0, n = props.length - 1; i < n; ++i) { | |
obj = obj[props[i]] = obj[props[i]] || {}; | |
} | |
obj[props[i]] = val; | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment