Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pretty print JavaScript objects (does not conform to JSON, because we don't want escape sequences in string literals)
function isPlainObject(o) {
return o && toString.call(o) === '[object Object]' && 'isPrototypeOf' in o;
}
function isArray(o) {
return toString.call(o) == '[object Array]';
}
function objectToString(val) {
var INDENT = '  ';
var lines = [];
_objectToString(val, 0, lines);
return lines.join('<br />');
function _makeIndent(nestDepth) {
var indent = '';
for (var i = 0; i < nestDepth; i++) {
indent += INDENT;
}
return indent;
}
function _makeLine(val, nestDepth, propName) {
var indent = _makeIndent(nestDepth);
propName = propName && propName + ': ' || '';
return indent + propName + val;
}
function _objectToString(val, nestDepth, lines, propName) {
var indent = _makeIndent(nestDepth);
if (isPlainObject(val)) {
lines.push(indent + '{');
for (var prop in val) {
_objectToString(val[prop], nestDepth + 1, lines, prop);
}
lines.push(indent + '}');
} else if (isArray(val)) {
lines.push(indent + '[');
for (var i = 0; i < val.length; i++) {
_objectToString(val[i], nestDepth + 1, lines);
}
lines.push(indent + ']');
} else {
lines.push(_makeLine(val, nestDepth, propName));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment