Created
November 16, 2016 15:21
-
-
Save awerlang/ebfdaaefde81b51ab809f73ec4555272 to your computer and use it in GitHub Desktop.
Convert to JSON, replacing cyclic dependencies
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 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