Display JS object
Display JS object test
by roge roge
HTML
<h1>Display JS object</h1>
<pre id="Canvas"></pre>
CSS
*{ font: 11pt monospace, Consolas, sans-serif,Arial,Verdana;
font-weight: normal;
color:#444;
}
pre {
font: 10pt monospace, Consolas, sans-serif,Arial,Verdana;
color:#44bb44;
}
JavaScript
const COMMA = ',';
function getIndentString(indent) {
var tab = ' ';
var str = '';
for(var i = 0; i < indent; i++) str += tab;
return str;
}
function dumpObject(obj, indent) {
var html = '';
if (Array.isArray(obj)) {
html += '[';
var nbProps = Object.keys(obj).length;
var indentStr= getIndentString(indent);
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
html += dumpObject(obj[i], indent);
if (i < nbProps - 1) html += COMMA;
}
}
html += ']';
} else if (typeof obj === 'object') {
html += '{';
var nbProps = Object.keys(obj).length;
var indentStr = getIndentString(indent);
var idx = 1;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
html += '\n' + indentStr + '"' + key + '": ' + dumpObject(obj[key], indent + 1);
if (idx < nbProps) html += COMMA;
idx ++;
}
}
html += '\n' + indentStr + '}';
} else if (typeof obj === 'string') {
html += '"' + obj + '"';
} else if (typeof obj === 'number') {
html += obj;
} else {
html += "+++ Type: " + (typeof obj);
}
return html;
}
var obj = {}
obj.title = "My Title";
obj.elements = [];
obj.elements.push("Simple text");
obj.elements.push({"name": "Alex", "firstname": "Mitchel"});
obj.elements.push("Another simple text");
obj.value = {};
document.getElementById("Canvas").innerHTML = dumpObject(obj, 0);