Search code examples
jqueryarraysjsonecmascript-5

How to debug circular reference that JSON.stringify is reporting


I'm getting a circular reference exception when calling JSON stringify, but I can't find the circular reference. It seems jQuery is the culprit here, but I don't see the issue and can't step into JSON stringify.

const list = $('.use-in-reporting-checkbox:checkbox:checked').map(function() 
{
    return this.value;
});

const dataPacket = {
    datasetIDs: list
};

try {
    const real = JSON.stringify(dataPacket);

} catch (error) {
    processError(error);
}

"Error reports: Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    property 'selectorData' -> object with constructor 'Object'
    |     property 'elements' -> object with constructor 'Array'
    --- index 0 closes the circle"

But, inspection of dataPacket just shows: "datasetIDs init (37)" with the 
list of checkbox values. Not sure how to debug this.

Solution

  • This error occurs because you get jQuery object instead of required value.

    .map-method returns jQuery-object, that should be resolved by get-call:

    const ids = $('.use-in-reporting-checkbox:checkbox:checked').map(function() 
    {
        return this.id;
    }).get();
    

    Alternative way:

    const ids = jQuery.map($('.use-in-reporting-checkbox:checkbox:checked'), function(v) 
    {
        return v.id;
    });