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).
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With