Skip to content

Instantly share code, notes, and snippets.

@WyrdNexus
Forked from bennettmcelwee/stringify.js
Created November 19, 2022 09:20
Show Gist options
  • Save WyrdNexus/0531f4318ba3eda8639f9cb79c16893a to your computer and use it in GitHub Desktop.
Save WyrdNexus/0531f4318ba3eda8639f9cb79c16893a to your computer and use it in GitHub Desktop.
Version of JSON.stringify limitied to a specific depth.
function stringifyMaxDepth (obj, depth = 1) {
// recursion limited by depth arg
if (!obj || typeof obj !== 'object') return JSON.stringify(obj)
let curDepthResult = '"<?>"' // too deep
if (depth > 0) {
curDepthResult = Object.keys(obj)
.map( (key) => {
let val = stringifyMaxDepth(obj[key], depth - 1)
if (val === undefined) val = 'null'
return `"${key}": ${val}`
})
.join(', ')
curDepthResult = `{${curDepthResult}}`
}
return JSON.stringify(JSON.parse(curDepthResult))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment