Created
November 30, 2010 13:44
-
-
Save FrankGrimm/721694 to your computer and use it in GitHub Desktop.
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 setNestedJSON = function(on, path, value) { | |
if (!(path instanceof Array)) { | |
path = path.split('\.'); | |
} | |
if (path && path.length > 0) { | |
var current = on; | |
var key = null; | |
while((key = path.shift()) != null) { | |
// make sure key exists at the current level | |
if (!current[key]) { | |
current[key] = {}; | |
} | |
if (path.length == 0) { | |
// last level, set value | |
current[key] = value; | |
return true; | |
} | |
// advance one level | |
current = current[key]; | |
} | |
} | |
return false; | |
} | |
var a = {'a':'b', 'b': {'c':'d', 'e':'f'}}; | |
console.log(a); | |
setNestedJSON(a, 'b.c', 42); | |
console.log(a); | |
setNestedJSON(a, 'b.d', 42.5); | |
console.log(a); | |
setNestedJSON(a, 'c', {'foo':'bar'}); | |
console.log(a); | |
setNestedJSON(a, 'c.baz', 'foobaz'); | |
console.log(a); | |
setNestedJSON(a, ['c', 'baz'], '1234'); | |
console.log(a); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment