Guest User

Untitled

a guest
Jul 16th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. function setNestedJSON (on, path, value) {
  2. if (!(path instanceof Array)) {
  3. path = path.split('\-');
  4. }
  5.  
  6. if (path && path.length > 0) {
  7. var current = on;
  8. var key = null;
  9.  
  10. while((key = path.shift()) != null) {
  11. // make sure key exists at the current level
  12. if (!current[key]) {
  13. current[key] = {};
  14. }
  15. if (path.length == 0) {
  16. // last level, set value
  17. current[key] = value;
  18. return true;
  19. }
  20. // advance one level
  21. current = current[key];
  22. }
  23. }
  24. return false;
  25. }
  26.  
  27. function deleteNestedJSON (on, path) { // TODO....
  28. if (!(path instanceof Array)) {
  29. path = path.split('\-');
  30. }
  31.  
  32.  
  33. if (path && path.length > 0) {
  34. if (path.length == 1) {
  35. delete on[path[0]]
  36. }
  37. if (on[path[0]] instanceof Object) {
  38. deleteNestedJSON(on[path[0]], path.slice(1))
  39. }
  40. }
  41. }
  42.  
  43. function cleanNestedJSON (obj) {
  44. if (obj instanceof Object) {
  45. var keys = Object.keys(obj)
  46. for (var i = keys.length - 1; i >= 0; i--) {
  47. if (obj[keys[i]] instanceof Object) {
  48. cleanNestedJSON(obj[keys[i]])
  49. if (Object.keys(obj[keys[i]]).length === 0) {
  50. delete obj[keys[i]]
  51. }
  52. }
  53. }
  54. }
  55. }
Add Comment
Please, Sign In to add comment