Why does $().map Produces Circular Reference

javascript, jquery

Solution

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.

Problem

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).

Original source