Created
June 1, 2024 10:39
-
-
Save Mazday21/c570c4c27a27cc9581135cc3a2328035 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
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