Created
July 24, 2009 03:01
-
-
Save furf/153813 to your computer and use it in GitHub Desktop.
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
var setDeepValue = function(obj, deepProp, val) { | |
var props = deepProp.split('.'), | |
root = obj, | |
i, n, p, t; | |
for (i = 0, n = props.length - 1; i < n; ++i) { | |
p = props[i]; | |
t = typeof obj[p]; | |
obj = obj[p] = (t === 'object' || t === 'function') ? obj[p] : {}; | |
} | |
obj[props[i]] = val; | |
return root; | |
}; | |
// Example: | |
var foo = {}; | |
setDeepValue(foo, 'deeply.nested.property', 'bar'); | |
// Added return to allow building of new objects | |
var obj = setDeepValue({}, 'deeply.nested.property', 'bar'); | |
/** | |
* foo = { | |
* deeply: { | |
* nested: { | |
* property: 'bar' | |
* } | |
* } | |
* } | |
*/ | |
var getDeepValue = function(obj, deepProp) { | |
var props = deepProp.split('.'), | |
i, n; | |
for (i = 0, n = props.length; i < n; ++i) { | |
if (typeof (obj = obj[props[i]]) === 'undefined') { | |
return; | |
} | |
} | |
return obj; | |
}; | |
// Example: | |
var val = getDeepValue(foo, 'deeply.nested.property'); // val = bar | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment