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
}
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
}
1 Answer
Reset to default 12You 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.
addObj
? – John Montgomery Commented Jul 26, 2019 at 22:31obj
is an identifier not a value, the actual value thatobj
refers to must be either the same object asthis
, or a different object that has a reference to (a reference to (a reference to (...)))this
or some other object in that chain. – Paul Commented Jul 26, 2019 at 22:32let l1 = new List(); l1.addObj(1, {a: 11});
current list: {"1":{"a":11}}. Works as expected . – ford04 Commented Jul 26, 2019 at 22:36