Created
December 2, 2010 21:36
-
-
Save Wizek/726126 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
function setNestedJSON (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; | |
} | |
function deleteNestedJSON (on, path) { // TODO.... | |
if (!(path instanceof Array)) { | |
path = path.split('\-'); | |
} | |
if (path && path.length > 0) { | |
if (path.length == 1) { | |
delete on[path[0]] | |
} | |
if (on[path[0]] instanceof Object) { | |
deleteNestedJSON(on[path[0]], path.slice(1)) | |
} | |
} | |
} | |
function cleanNestedJSON (obj) { | |
if (obj instanceof Object) { | |
var keys = Object.keys(obj) | |
for (var i = keys.length - 1; i >= 0; i--) { | |
if (obj[keys[i]] instanceof Object) { | |
cleanNestedJSON(obj[keys[i]]) | |
if (Object.keys(obj[keys[i]]).length === 0) { | |
delete obj[keys[i]] | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment