Javascript: TypeError: value of a circular object

I am trying to align a javascript object, however, when I do this, we get the following error:

TypeError: value of a cyclic object

I don’t think my code contains any circular references (newServiceObject is not mentioned inside the object), so I don’t understand why I am getting this message.

I want to turn my object containing two properties and an array into one 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 is on the last line (JSON.Stringify ()), but I have no idea why!

+6
source share
2 answers

This is usually because you are trying to serialize a JavaScript object that has properties pointing to each other in a loop.

In your example, newServiceObject.serviceCodeElemList points to a jQuery object that has loops in it: A context property that points to a document object. The document object has pointers to DOM elements that have pointers back to the document using 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> 
+4
source

Found it!

My problem was that when using jquery to build the array, I had to include the ToArray () method after the map function.

  var serviceCodeElemList = $(".ServiceCodeName").map(function() { return $(this).html(); } ).ToArray(); 

Therefore, when an array is included in an object, it is a standard array, not a jquery object.

+2
source

All Articles