Last active
April 17, 2018 14:51
-
-
Save codermarcos/9b23617c3ace559e9efaf12cb58cc2b5 to your computer and use it in GitHub Desktop.
Resolvendo cyclic object value
This file contains 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
var a = {}; | |
var b = {}; | |
a.b = b; // Cria a referencia em a para o B | |
b.a = a; // Cria a referencia em b para o A | |
JSON.stringifyCiclic = (json) => { | |
var seen = []; | |
var replacer = (key, value) => { | |
if (value != null && typeof value == 'object') { | |
if (seen.indexOf(value) >= 0) return; | |
seen.push(value); | |
} | |
return value; | |
}; | |
return JSON.stringify(json, replacer); | |
} | |
var string_a = JSON.stringifyCiclic(a); | |
var string_b = JSON.stringifyCiclic(b); | |
console.log(a); | |
// a: Object { b: [circular object] } | |
console.log(string_a); | |
// "{'b':{}}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment