Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does $().map Produces Circular Reference

Chrome's array.map works fine, but jQuery's .map produces a circular reference somehow. I can't see any evidence of a circular reference using console.log, but JSON.stringify throws Uncaught TypeError: Converting circular structure to JSON in the second block.

Run it on JSFiddle: http://jsfiddle.net/langdonx/vQBak/

Or check the code:

var callback = function(index, element) {
    return {
        "index": index
    };
};

var array1 = ["1", "2"];
var mappedArray1 = array1.map(callback);
console.log(mappedArray1);
var json1 = JSON.stringify(mappedArray1);
console.log(json1);

var jqueryArray2 = $('body > div');
var mappedArray2 = jqueryArray2.map(callback);
console.log(mappedArray2);
var json2 = JSON.stringify(mappedArray2); // Chokes with "Uncaught TypeError: Converting circular structure to JSON"
console.log(json2);​

Yes, I'm using the same callback, and yes ECMAScript's map passes the arguments in a different order, but it shouldn't matter for this example, as they're all simple types (string, number).

like image 258
Langdon Avatar asked Jul 18 '12 14:07

Langdon


People also ask

How do you prevent converting circular structure to JSON?

The "Converting circular structure to JSON" error occurs when we pass an object that contains circular references to the JSON. stringify() method. To solve the error, make sure to remove any circular references before converting the object to JSON.

What is circular reference in JSON?

A circular structure is an object that references itself. In the example below, we are referencing the object (obj) as a value for the location key.

What does circular mean in JavaScript?

Circular reference is a series of references where an object references itself directly or indirectly through a series of objects, resulting in a closed loop, appearing in most computer programming including JavaScript.

What is MAP operator in JavaScript?

map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.


1 Answers

The jQuery .map() function returns a jQuery object containing an array, not an actual array, which may be an important difference. Try calling:

var json2 = JSON.stringify(mappedArray2.get());

The call to .get() will return the actual array rather than a jQuery object.

like image 83
Anthony Grist Avatar answered Sep 28 '22 17:09

Anthony Grist