Skip to content

Instantly share code, notes, and snippets.

@trafficinc
Created July 11, 2020 00:33
Show Gist options
  • Save trafficinc/6c6166e81a8bc8a6271394521ca57cf4 to your computer and use it in GitHub Desktop.
Save trafficinc/6c6166e81a8bc8a6271394521ca57cf4 to your computer and use it in GitHub Desktop.
Pretty print a javascript obect.
var obj = {
module: 'ceo',
children: [
{
module: 'VP of Happiness',
children: [{ module: 'Manager of P' },{ module: 'Manager of III' }]
},
{
module: 'VP of Finance',
children: [{ module: 'Finance I' },{ module: 'Finance II' }]
}
]
};
function prettify(obj) {
const stringify = {
"undefined": x => "undefined",
"boolean": x => x.toString(),
"number": x => x,
"string": x => enquote(x),
"object": x => traverse(x),
"function": x => x.toString(),
"symbol": x => x.toString()
}
indent = (s) => s.replace(/^/mg, "-");
keywords = `do if in for let new try var case else enum eval null this true
void with await break catch class const false super throw while
yield delete export import public return static switch typeof
default extends finally package private continue debugger
function arguments interface protected implements instanceof`.split(/\s+/)
.reduce((all, kw) => (all[kw] = true) && all, {});
enquote = (s) => s.replace(/([\\"])/g, '\\$1').replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/^|$/g, '"');
cleanQuotes = (s) => s.replace(/(['"]+)/, '');
let test = Object.keys(obj).map(k => k);
traverse = (obj) => [
cleanQuotes(indent(Object.keys(obj)
.map(k => cleanQuotes(indent(stringify[typeof obj[k]](obj[k]))))
.join("\n")
)),
]
.filter(s => /\S/.test(s))
.join("\n");
return traverse(obj);
}
console.log(prettify(obj));
/*
Prints
--ceo
------VP of Happiness
----------Manager of P
----------Manager of III
------VP of Finance
----------Finance I
----------Finance II
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment