Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix circular reference in javascript object?

lets say there's a list object properties are added to this list whereas the property name is a string id, and the value is another object

class List {
  constructor() {
    this.list = {}
  }
  addObj(id, obj) {
    this.list[id] = obj;
    --> console.log("current list: " + JSON.stringify(this.list))
  }
}

the issue is that in the console, this returns TypeError: Converting circular structure to JSON at the --> line

I understand the concept of circular references, but clearly im not understanding enough. Why can I not log/stringify this.list?

if id is a string "123456", and the value is obj, I expect this.list to be displayed as: { '123456': obj }

like image 813
Jim Avatar asked Jul 23 '26 06:07

Jim


1 Answers

You can't "fix" that in a sense if you can't change the underlying data structure of the objects you store but you can wrap the serialization with try/catch to save your program from crashing if not all of them have circular references. The reason why you get this issue is that one of the objects you pass as a second argument to addObj has a circular reference(s) to itself or to other objects that point to that object. For example:

const obj = {prop: 42};
const anotherObj = {prop: 24};
anotherObj.someRef = obj;
obj.someRef = anotherObj;
const list = new List();
list.addObj('some', obj);

Consequently, we get a runtime error saying we have circular references:

Uncaught TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    |     property 'someRef' -> object with constructor 'Object'
    --- property 'someRef' closes the circle

That's because JSON can't serialize cyclic data structures by design.

If that console.log statement has been added just for the debugging purposes, please, don't do that and use breakpoints in ChromeDevTools.

like image 86
Viacheslav Moskalenko Avatar answered Jul 24 '26 20:07

Viacheslav Moskalenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!