Detecting and fixing circular references in JavaScript

后端 未结 15 869
庸人自扰
庸人自扰 2020-11-28 23:29

Given I have a circular reference in a large JavaScript object

And I try JSON.stringify(problematicObject)

And the browser throws

15条回答
  •  甜味超标
    2020-11-29 00:19

    Here is MDN's approach to detecting and fixing circular references when using JSON.stringify() on circular objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value :

    In a circular structure like the following

    var circularReference = {otherData: 123};
    circularReference.myself = circularReference;
    

    JSON.stringify() will fail:

    JSON.stringify(circularReference);
    // TypeError: cyclic object value
    

    To serialize circular references you can use a library that supports them (e.g. cycle.js) or implement a solution by yourself, which will require finding and replacing (or removing) the cyclic references by serializable values.

    The snippet below illustrates how to find and filter (thus causing data loss) a cyclic reference by using the replacer parameter of JSON.stringify():

    const getCircularReplacer = () => {
          const seen = new WeakSet();
          return (key, value) => {
            if (typeof value === "object" && value !== null) {
              if (seen.has(value)) {
                return;
              }
              seen.add(value);
            }
            return value;
          };
        };
    
    JSON.stringify(circularReference, getCircularReplacer());
    // {"otherData":123}
    

提交回复
热议问题