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.
// Similar to JSON.stringify but limited to a specified depth (default 1)
const stringify = (obj, depth) => {
if (depth === undefined) {
depth = 1 // default
}
return ( ! obj) ?
JSON.stringify(obj) :
(typeof obj === 'object') ?
'{' + (depth < 1 ? '?' : (
Object.keys(obj).map((k) => k + ': ' + stringify(obj[k], depth - 1)).join(', ')
)) + '}' :
JSON.stringify(obj)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment