Guest User

Untitled

a guest
Jun 23rd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. //your object
  2. var o = {
  3. foo:"bar",
  4. arr:[1,2,3],
  5. subo: {
  6. foo2:"bar2"
  7. }
  8. };
  9.  
  10. //called with every property and it's value
  11. function process(key,value) {
  12. log(key + " : "+value);
  13. }
  14.  
  15. function traverse(o,func) {
  16. for (i in o) {
  17. func.apply(this,[i,o[i]]);
  18. if (typeof(o[i])=="object") {
  19. //going on step down in the object tree!!
  20. traverse(o[i],func);
  21. }
  22. }
  23. }
  24.  
  25. //that's all... no magic, no bloated framework
  26. traverse(o,process);
  27.  
  28. $.each(myJsonObj, function(key,val){
  29. // do something with key and val
  30. });
  31.  
  32. function traverse(jsonObj) {
  33. if( typeof jsonObj == "object" ) {
  34. $.each(jsonObj, function(k,v) {
  35. // k is either an array index or object key
  36. traverse(v);
  37. }
  38. }
  39. else {
  40. // jsonOb is a number or string
  41. }
  42. }
  43.  
  44. function js_traverse(o) {
  45. var type = typeof o
  46. if (type == "object") {
  47. for (var key in o) {
  48. print("key: ", key)
  49. js_traverse(o[key])
  50. }
  51. } else {
  52. print(o)
  53. }
  54. }
  55.  
  56. js> foobar = {foo: "bar", baz: "quux", zot: [1, 2, 3, {some: "hash"}]}
  57. [object Object]
  58. js> js_traverse(foobar)
  59. key: foo
  60. bar
  61. key: baz
  62. quux
  63. key: zot
  64. key: 0
  65. 1
  66. key: 1
  67. 2
  68. key: 2
  69. 3
  70. key: 3
  71. key: some
  72. hash
  73.  
  74. function traverse(o,func) {
  75. for (i in o) {
  76. func.apply(this,[i,o[i]]);
  77. if (typeof(o[i])=="object") {
  78. //going on step down in the object tree!!
  79. traverse(o[i],func);
  80. }
  81. }
  82. }
Add Comment
Please, Sign In to add comment