Skip to content

Instantly share code, notes, and snippets.

@phunanon
Created October 5, 2024 13:59
Show Gist options
  • Select an option

  • Save phunanon/d941e578abcaf4e33114d246dcfb5b4d to your computer and use it in GitHub Desktop.

Select an option

Save phunanon/d941e578abcaf4e33114d246dcfb5b4d to your computer and use it in GitHub Desktop.
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