Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I couldn't find an answer which handled circulars, and I also decided to do this without any unnecessary DOM writes. Also, I didn't follow the exact mark-up the OP requested because I felt nesting tables was more convenient for a recursive operation such as this- and serves close to the same visual purpose.</p> <p>So, here's the function I've created:</p> <pre><code>function dataToTable (data) { var storage = []; return (function buildTable (data) { var table = '&lt;table&gt;&lt;tbody&gt;'; var name, value; // Add the object/array to storage for cirular detection. storage.push(data); for (name in data) { value = data[name]; table += '&lt;tr&gt;&lt;td&gt;' + name + '&lt;/td&gt;&lt;td&gt;'; // If the value is an object we've put in storage (circular) if (storage.indexOf(value) !== -1) { table += '&lt;em&gt;Circular&lt;/em&gt;'; } else if (typeof value === 'object') { table += buildTable(value); } else { table += value; } table += '&lt;/td&gt;&lt;/tr&gt;'; } return table + '&lt;/tbody&gt;&lt;/table&gt;'; }(data)); } </code></pre> <p>Here is the object I used to test:</p> <pre><code>var obj = { a : { x : 1, y : 2, z : 3 }, b : { x : 1, y : 2, z : { test1: 0, test2: { test3: 1, test4: ['a','b','c'] } } } }; obj.c = obj; obj.b.z.test2.test4.push(obj.a); </code></pre> <p>The function will turn this object into an HTML table. What you do with the table is up to you. On my fiddle, I used the DOM to add the table to a DIV (document.getElementById).</p> <p><a href="http://jsfiddle.net/5RhXF/1/" rel="nofollow">http://jsfiddle.net/5RhXF/1/</a></p> <p>I hope you'll find my implementation clear.</p> <p>UPDATE::</p> <p>I decided to test this on the jQuery library, and it worked! Except, the functions were printing as their toString value with no good format for text.. Which makes sense, but not very helpful. So, I'm thinking this is a nice and easy way to look through APIs for frameworks/libraries and what-not. Therefore, I added prettify for syntax-highlighting of functions, and also added a type-check for functions in the table generator, and a quick class to get rid of borders around the prettify box (as there's already a border on the table cell). If anyone is interested in the version designed for source-reading/debugging, here's the fiddle:</p> <p><a href="http://jsfiddle.net/5RhXF/7/" rel="nofollow">http://jsfiddle.net/5RhXF/7/</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload