Skip to content

Instantly share code, notes, and snippets.

@FrankGrimm
Created November 30, 2010 13:44
Show Gist options
  • Save FrankGrimm/721694 to your computer and use it in GitHub Desktop.
Save FrankGrimm/721694 to your computer and use it in GitHub Desktop.
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