Detecting and fixing circular references in JavaScript

后端 未结 15 867
庸人自扰
庸人自扰 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:06

    Try using console.log() on the chrome/firefox browser to identify where the issue encountered.

    On Firefox using Firebug plugin, you can debug your javascript line by line.

    Update:

    Refer below example of circular reference issue and which has been handled:-

    // JSON.stringify, avoid TypeError: Converting circular structure to JSON
    // Demo: Circular reference
    var o = {};
    o.o = o;
    
    var cache = [];
    JSON.stringify(o, function(key, value) {
        if (typeof value === 'object' && value !== null) {
            if (cache.indexOf(value) !== -1) {
                // Circular reference found, discard key
                alert("Circular reference found, discard key");
                return;
            }
            alert("value = '" + value + "'");
            // Store value in our collection
            cache.push(value);
        }
        return value;
    });
    cache = null; // Enable garbage collection
    
    var a = {b:1};
    var o = {};
    o.one = a;
    o.two = a;
    // one and two point to the same object, but two is discarded:
    JSON.stringify(o);
    
    var obj = {
      a: "foo",
      b: obj
    };
    
    var replacement = {"b":undefined};
    
    alert("Result : " + JSON.stringify(obj,replacement));
    

    Refer example LIVE DEMO

提交回复
热议问题