Last active
June 26, 2025 20:50
-
-
Save westc/9a7fd947a3a8a414cc280fc5ace9bca8 to your computer and use it in GitHub Desktop.
copyJSON() - An easy way to copy values while allowing circular references to be omitted.
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
/** | |
* @template T | |
* @param {T} value | |
* @param {boolean} [omitCircularRefs=false] | |
* @returns {T} | |
*/ | |
function copyJSON(value, omitCircularRefs = false) { | |
const ancestors = new WeakSet(); | |
function recurse(value) { | |
if ('object' !== typeof value || value === null) return value; | |
let returnValue = Array.isArray(value) ? [] : {}; | |
ancestors.add(value); | |
for (const [k, v] of Object.entries(value)) { | |
if (!ancestors.has(v)) { | |
returnValue[k] = recurse(v); | |
} | |
} | |
ancestors.delete(value); | |
return returnValue; | |
} | |
return JSON.parse(JSON.stringify((omitCircularRefs ? recurse(value) : value) ?? null)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment