Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: TypeError: cyclic object value

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!

like image 916
Neil P Avatar asked Sep 01 '15 14:09

Neil P


2 Answers

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>
like image 147
Juan Mendes Avatar answered Oct 02 '22 10:10

Juan Mendes


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.

like image 26
Neil P Avatar answered Oct 02 '22 09:10

Neil P