Created
July 11, 2020 00:33
-
-
Save trafficinc/6c6166e81a8bc8a6271394521ca57cf4 to your computer and use it in GitHub Desktop.
Pretty print a javascript obect.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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