Skip to content

Instantly share code, notes, and snippets.

@westc
Last active June 26, 2025 20:50
Show Gist options
  • Save westc/9a7fd947a3a8a414cc280fc5ace9bca8 to your computer and use it in GitHub Desktop.
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.
/**
* @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