From a1363905e8383fe217d49347757213f237aa8508 Mon Sep 17 00:00:00 2001 From: RealPeha Date: Tue, 6 Oct 2020 11:27:49 +0300 Subject: [PATCH] Added circularJSONStringify snippet --- snippets/circularJSONStringify.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 snippets/circularJSONStringify.md diff --git a/snippets/circularJSONStringify.md b/snippets/circularJSONStringify.md new file mode 100644 index 000000000..d181e018c --- /dev/null +++ b/snippets/circularJSONStringify.md @@ -0,0 +1,30 @@ +--- +title: circularJSONStringify +tags: object,intermediate +--- + +Serializes valid JSON objects containing circular references into a JSON format. + +- Use `JSON.stringify` with a custom replacer +- ⚠️ **NOTICE:** This function finds and removes circular references, what causes data loss + +```js +const circularJSONStringify = object => { + const cache = new WeakSet(); + return JSON.stringify(object, (key, value) => { + if (value !== null && typeof value === 'object') { + if (cache.has(value)) return; + + cache.add(value); + } + return value; + }); +}; +``` + +```js +const obj = { n: 42 }; +obj.obj = obj; + +circularJSONStringify(obj); // '{"n": 42}' +```