Skip to content

Instantly share code, notes, and snippets.

@codermarcos
Last active April 17, 2018 14:51
Show Gist options
  • Save codermarcos/9b23617c3ace559e9efaf12cb58cc2b5 to your computer and use it in GitHub Desktop.
Save codermarcos/9b23617c3ace559e9efaf12cb58cc2b5 to your computer and use it in GitHub Desktop.
Resolvendo cyclic object value
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