Advertisement
Guest User

Untitled

a guest
Apr 26th, 2015
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. var myObject = [{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10,"children":[{"id":11,"children":[{"id":12}]}]}]}];
  2.  
  3. function iterateJson(obj) {
  4. $.each(obj, function(key, val) {
  5. if(val && typeof val === "object") { // object, call recursively
  6. iterateJson(val);
  7. } else {
  8. console.log(key + ' => ' + val);
  9. }
  10. });
  11. }
  12. iterateJson(myObject);
  13.  
  14. <!DOCTYPE html>
  15. <html>
  16. <title>Stack jQuery</title>
  17. <link rel="stylesheet" href="../repo/css/bootstrap.css" type="text/css" />
  18. <script src="https://code.jquery.com/jquery-2.1.3.js"></script>
  19. <script src="../repo/js/bootstrap.js"></script>
  20. <script src="../repo/js/jquery.validate.js"></script>
  21. <head></head>
  22. <body>
  23. <div class="showResult">
  24. </div>
  25.  
  26. <script>
  27. var data = [{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10,"children":[{"id":11,"children":[{"id":12}]}]}]}]
  28.  
  29. var htmlElem = '<ul>';
  30. $.each(data, function(key, value){
  31. htmlElem += '<li>'+value.id+'<ul>';
  32. if(typeof(value.children) == 'object'){
  33. $.each(value.children, function(keyId, val){
  34. htmlElem += '<li>'+val.id+'</li>';
  35. });
  36. }
  37. htmlElem += '</ul></li>';
  38.  
  39. $('.showResult').html(htmlElem);
  40. });
  41. htmlElem += '</ul>';
  42. </script>
  43. </body>
  44. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement