Skip to content

Instantly share code, notes, and snippets.

@sturmenta
Last active November 19, 2022 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sturmenta/2fdc967bbe6f7a6c76d6f5ff025fe323 to your computer and use it in GitHub Desktop.
Save sturmenta/2fdc967bbe6f7a6c76d6f5ff025fe323 to your computer and use it in GitHub Desktop.
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;
@sturmenta
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment