Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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]]
- }
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment