Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Version of JSON.stringify limitied to a specific depth.
export const stringifyWithCustomDepth = (obj: any, depth = 1): string => {
return !obj
? JSON.stringify(obj, null, 2)
: typeof obj === 'object'
? JSON.stringify(
JSON.parse(
depth < 1
? '"???"'
: `{${Object.keys(obj)
.map((k) => `"${k}": ${stringifyWithCustomDepth(obj[k], depth - 1)}`)
.join(', ')}}`,
),
null,
2,
)
: JSON.stringify(obj, null, 2);
};
export default stringifyWithCustomDepth;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment