This question has already been answered:

There is an object

let man = { "name":"Pasha", "age":20, }; man.friend = man; 

It must be serialized. JSON.stringify(man) throws the error Converting circular structure to JSON

 let man = { "name":"Pasha", "age":20, }; man.friend = man; JSON.stringify(man) 
PS: In response, he sketched a crutch for this task. Maybe there are better options?

Reported as a duplicate at Grundy. javascript 22 Sep '18 at 19:16 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    2 answers 2

     let man = { "name":"Pasha", "age":20, }; man.friend = Object.assign({},man); console.log(JSON.stringify(man)); 

    • Interesting. In essence, my goal was to serialize more looped objects. Type response, request on the server NodeJs , and in the question object is given as an example. My way works for objects of any nesting. Your option should somehow be integrated there - Dmytryk
    • @ Dmytryk, it makes no sense to try to serialize request , response , given that there may be values ​​that can not be serialized in principle. Better to just pick the fields you want - Grundy
    • @Grundy, there are many different objects on the server. And all of their fields, I do not know. I wanted to be able to inspect them in the browser console) - Dmytryk
    • @ Dmytryk, All of them know and not necessary. For this there is a certificate in which everything is described. - Grundy
    • one
      @Grandy, for sure. But, anyway, thanks to this option, I had an idea how to improve my code). I'll change it now. The result exceeded all my expectations) It turned out full serialization) - Dmytryk

     let man = { "name":"Pasha", "age":20, }; man.friend = man; let arr=[]; function removeCircular(obj){ //проходим циклом по всем ключам for (key in obj){ let testObj = obj[key] //каждый ключ пробуем сериализовать try{ JSON.stringify(testObj) //если не получается, добавляем этот ключ (а по сути объект) в массив }catch(err){ arr.push(testObj); //проверяем ключ, на идентичность (объекты для сравнения лежат в массиве) let d = checkInstanse(testObj); // если идентичных объектов найдено не было - ищем идентичности внутри этого ключа(объекта) if(!d){ removeCircular(testObj) } else{ delete obj[key] obj[key] = Object.assign({}, obj) } } } } function checkInstanse(obj){ let returnObj; for (let i=0; i<arr.length; i++){ if (Object.is(arr[i], obj)){ returnObj = obj; } } return returnObj } removeCircular(man); console.log(JSON.stringify(man));