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
Find the problem I recently encountered a problem...
Today, I set up a newly purchased Alibaba Cloud E...
PHP related paths in Ubuntu environment PHP path ...
1. What is HTML markup language? HTML is a markup...
This article describes how to install mysql5.6 us...
Table of contents A. Docker deployment of springb...
Preface Arrays are a special kind of object. Ther...
This article records the installation tutorial of...
View Database show databases; Create a database c...
1. Download: http://www.oracle.com/technetwork/ja...
This article shares the installation and configur...
Link: https://qydev.weixin.qq.com/wiki/index.php?...
Introduction: When I looked at interview question...
What is a directive? Both Angular and Vue have th...
Click here to return to the 123WORDPRESS.COM HTML ...