Last active
November 19, 2022 09:20
-
-
Save bennettmcelwee/06f0cadd6a41847f848b4bd2a351b6bc to your computer and use it in GitHub Desktop.
Version of JSON.stringify limitied to a specific depth.
This file contains 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
// Similar to JSON.stringify but limited to a specified depth (default 1) | |
// The approach is to prune the object first, then just call JSON.stringify to do the formatting | |
const prune = (obj, depth = 1) => { | |
if (Array.isArray(obj) && obj.length > 0) { | |
return (depth === 0) ? ['???'] : obj.map(e => prune(e, depth - 1)) | |
} else if (obj && typeof obj === 'object' && Object.keys(obj).length > 0) { | |
return (depth === 0) ? {'???':''} : Object.keys(obj).reduce((acc, key) => ({ ...acc, [key]: prune(obj[key], depth - 1)}), {}) | |
} else { | |
return obj | |
} | |
} | |
const stringify = (obj, depth = 1, space) => JSON.stringify(prune(obj, depth), null, space) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you @bennettmcelwee and @sturmenta. I've adapted sturmenta's code back into native js, cleaned it up a bit, and added handling for
undefined
. Should be fairly efficient and robust now, as well as being easily adjusted to needs.