I am trying to stringify a javascript object, however when I do this a get the following error:
TypeError: cyclic object value
I don't believe that my code contains any cyclic references (newServiceObject is not referenced inside the object), so I do not understand why I am getting this message.
I want to turn my object that contains two properties and an array into a single string.
var serviceName = $('#newServiceNameBox').val();
var serviceCodeElemList = $(".ServiceCodeName").map(function() { return $(this).html(); } );
//create the new service object
var newServiceObject = {ServiceId:-1, ServiceName: serviceName, ServiceCodes: serviceCodeElemList };
var appendNewService = '&newService='+JSON.stringify(newServiceObject);
The error occurs on the last line (the JSON.Stringify() ) but I have no idea why!
This is typically because you are trying to serialize a JavaScript object that has properties that point to each other in a cycle.
In your example, newServiceObject.serviceCodeElemList
points to a jQuery
object which does have cycles in it: Its context
property which points to a document object. A document object has pointers to DOM elements that have pointers back to the document through the ownerDocument
property
var jqueryObj = $('div');
console.log(jqueryObj.context); // Document object
console.log(jqueryObj.context.body.firstChild.ownerDocument); // Document object
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
Found it!
My problem was that when using jquery to build the array, I should have included the ToArray() method after the map function.
var serviceCodeElemList = $(".ServiceCodeName").map(function() { return $(this).html(); } ).ToArray();
Therefore when the array is included in the object, it is a standard array and not 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