I'm working with a JSON object that looks like this:
var temp1 = {
name: "AMC",
children: [
{
name: "cde",
children: [
{
name: "AMC",
children: [
{
name: "cde",
children: [
{
name: "AMC",
children: [
//.............. continues as circular dependency
]
}
]
}
]
}
]
},
{
name: "mnp",
children: [
{
name: "xyz",
children: []
}
]
}
]
}
The issue I'm facing is that due to this circular dependency, JSON.stringify is failing. I've searched extensively for a solution but haven't found much help.
My goal is to detect the circular dependency in the json object and add a new key, 'circular: true', while removing all subsequent nodes.
Here is the desired output I am aiming for:
var temp1 = {
name: "AMC",
children: [
{
name: "cde",
circular: true,
children: [ // No children here as it is circular dependency
]
},
{
name: "mnp",
children: [
{
name: "xyz",
children: []
}
]
}
]
}
I believe there is a way to solve this problem by looping through all the children up to a maximum of 2 levels, but this method may miss valid children with depth greater than 3.
If my question isn't clear, please let me know and I can provide further clarification.