Skip to content

Instantly share code, notes, and snippets.

@awerlang
Created November 16, 2016 15:21
Show Gist options
  • Save awerlang/ebfdaaefde81b51ab809f73ec4555272 to your computer and use it in GitHub Desktop.
Save awerlang/ebfdaaefde81b51ab809f73ec4555272 to your computer and use it in GitHub Desktop.
Convert to JSON, replacing cyclic dependencies
function toJSON(object, fieldsToOmit) {
const map = new Map();
let index = 0;
return JSON.stringify(object, (key, value) => {
if (~fieldsToOmit.indexOf(key)) return undefined;
return value != null && typeof value === 'object'
? map.get(value) || (map.set(value, '$' + ++index), value)
: value;
}, 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment