Skip to content

Instantly share code, notes, and snippets.

@Mazday21
Created June 1, 2024 10:39
Show Gist options
  • Save Mazday21/c570c4c27a27cc9581135cc3a2328035 to your computer and use it in GitHub Desktop.
Save Mazday21/c570c4c27a27cc9581135cc3a2328035 to your computer and use it in GitHub Desktop.
export default function objectToString(obj, indent = '') {
const lines = ['{'];
const entries = Object.entries(obj);
let nestedIndentDiff = '';
entries.forEach(([key, value], index) => {
if (typeof value === 'object' && value !== null) {
let nestedIndent = `${indent} `;
if (key.startsWith('+') || key.startsWith('-')) {
nestedIndent = `${indent} `;
nestedIndentDiff += ' ';
}
const nestedLines = objectToString(value, nestedIndent);
lines.push(`${indent} ${key}: ${nestedLines}`);
} else {
lines.push(`${indent} ${key}: ${value}`);
}
if (index === entries.length - 1) {
const closingIndent = indent.replace(nestedIndentDiff, '');
lines.push(`${closingIndent}}`);
nestedIndentDiff = nestedIndentDiff.slice(0, -2);
}
});
return lines.join('\n');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment