Output javascript object to div recursively.


/ Published in: JavaScript
Save to your folder(s)

Outputs the contents of a javascript object to a div called #output. Can be useful in some circumstances


Copy this code and paste it in your HTML
  1. function outputData() {
  2. var ob = propertyBox.getObject();
  3. $("#output").html("");
  4.  
  5. var outputText = "<ul>";
  6. outputText += _outputRecursive(ob, "");
  7. outputText += "</ul>";
  8. $("#output").html(outputText);
  9. }
  10.  
  11.  
  12. function _outputRecursive(ob, text) {
  13. var text2 = text;
  14. for (var prop in ob) {
  15. if (!ob.hasOwnProperty(prop)) {
  16. continue;
  17. }
  18.  
  19. text2 += "<li>";
  20.  
  21. var val = ob[prop];
  22.  
  23. if (val instanceof Object && !(val instanceof Array)) {
  24. text2 += "<b>" + prop + "</b>";
  25. text2 += "<ul>" + _outputRecursive(val, "") + "</ul>";
  26. }
  27. else {
  28. if (val instanceof Array) {
  29. val = $.toJSON(val); // convert to string
  30. }
  31.  
  32. text2 += "<b>" + prop + "</b>: " + val;
  33. }
  34.  
  35. text2 += "</li>";
  36. }
  37. return text2;
  38. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.