-
-
Save WyrdNexus/0531f4318ba3eda8639f9cb79c16893a to your computer and use it in GitHub Desktop.
Version of JSON.stringify limitied to a specific depth.
This file contains hidden or 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
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