When programmers do TypeScript/JavaScript development on a daily basis, they often need to serialize complex JavaScript objects into JSON strings through JSON.stringify and save them locally for subsequent specific analysis. However, if the JavaScript object itself contains circular references, JSON.stringify does not work properly, with the error message:
The solution is to use the following code from this website to define a global cache array. Whenever the properties of the JavaScript object to be serialized are traversed, the value corresponding to the property is stored in the cache array. If you find that an attribute value already exists in the cache array during the traversal, it means that a circular reference has been detected. In this case, you can simply return to exit the loop. var cache = []; var str = JSON.stringify(o, function(key, value) { if (typeof value === 'object' && value !== null) { if (cache.indexOf(value) !== -1) { // remove return; } // Collect all values cache.push(value); } return value; }); cache = null; // Clear the variable to facilitate garbage collection Using this method, I successfully serialized a JavaScript object with a circular reference into a string. This concludes this article on how to solve the circular reference problem encountered when using JSON.stringify. For more information about JSON.stringify circular references, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Detailed tutorial for installing mysql5.7.18 on centos7.3
>>: Linux kernel device driver character device driver notes
Table of contents summary Basic Example motivatio...
Table of contents Index Type Index structure Nonc...
Mixin method: The browser cannot compile: The old...
The format is simple: proxy_pass URL; The URL inc...
What is a container data volume If the data is in...
Table of contents 1. Responsive principle foundat...
1. Download the required packages wget -P /usr/lo...
1. The Linux server configures /etc/hosts.deny to...
This method uses the drop-shadow filter in CSS3 t...
This article uses an example to describe how to v...
9 great JavaScript framework scripts for drawing ...
Table of contents 1. Project Integration 1. CDN i...
The establishment of MySQL index is very importan...
Pop-up windows are often used in actual developme...
Ubuntu 15.04 opens MySQL remote port 3306. All th...