Created
June 4, 2020 14:31
-
-
Save souhaiebtar/1722580b86715ce1177ba2c01bf11f31 to your computer and use it in GitHub Desktop.
[stringify circular Json structure] stringify circular json structure in javascript #js #javascript #circular
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
function cleanStringify(object) { | |
if (object && typeof object === 'object') { | |
object = copyWithoutCircularReferences([object], object); | |
} | |
return JSON.stringify(object); | |
function copyWithoutCircularReferences(references, object) { | |
var cleanObject = {}; | |
Object.keys(object).forEach(function(key) { | |
var value = object[key]; | |
if (value && typeof value === 'object') { | |
if (references.indexOf(value) < 0) { | |
references.push(value); | |
cleanObject[key] = copyWithoutCircularReferences(references, value); | |
references.pop(); | |
} else { | |
cleanObject[key] = '###_Circular_###'; | |
} | |
} else if (typeof value !== 'function') { | |
cleanObject[key] = value; | |
} | |
}); | |
return cleanObject; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment