Why $ (). Map Produces a Circular Link

Chrome array.map works fine, but jQuery .map calls a circular link. I don't see any evidence of a circular link using console.log , but JSON.stringify throws Uncaught TypeError: Converting circular structure to JSON into 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 use the same callback, and yes the ECMAScript map passes the arguments in a different order, but this does not matter in this example, since they are all simple types (string, number).

+8
javascript jquery
source share
1 answer

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

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

Calling .get() will return the actual array, not the jQuery object.

+19
source share

All Articles