Created
October 5, 2024 13:59
-
-
Save phunanon/d941e578abcaf4e33114d246dcfb5b4d to your computer and use it in GitHub Desktop.
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
| function formatObj(obj: object) { | |
| const lines: [number, string][] = []; | |
| function fmt(obj: any, depth: number) { | |
| if (Array.isArray(obj)) { | |
| if (!obj.length) { | |
| lines.push([depth, 'none']); | |
| } | |
| for (const x of obj) { | |
| fmt(x, depth); | |
| } | |
| } else if (typeof obj === 'object') { | |
| for (const [k, v] of Object.entries(obj)) { | |
| if (Array.isArray(v)) { | |
| if (v.length) { | |
| lines.push([depth, `${k}:`]); | |
| fmt(v, depth + 1); | |
| } else { | |
| lines.push([depth, `${k}: none`]); | |
| } | |
| } else if (typeof v !== 'object') { | |
| lines.push([depth, `${k}: ${v}`]); | |
| } else { | |
| lines.push([depth, `${k}:`]); | |
| fmt(v, depth + 1); | |
| } | |
| } | |
| } else { | |
| lines.push([depth, obj.toString()]); | |
| } | |
| } | |
| fmt(obj, 0); | |
| return lines | |
| .map(([depth, line]) => ' '.repeat(depth) + '- ' + line) | |
| .join('\n'); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment