Find any circular dependencies within a JSON object and eliminate all elements beyond a depth of two

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.

Answer №1

Through a clever recursive approach, the issue can be resolved:

function resolveCircularDependency(stack, parent, objToCheck){
    stack = stack || []; //stack serves as a record of previous names encountered
    var foundMatch = stack.find(function(parent){
        return (parent == objToCheck.name && objToCheck.children.length > 0); //determines if the current object's name matches any in the stack.
    });
    
    if(!foundMatch && objToCheck.children.length > 0){
        stack.push(objToCheck.name); //adds the current object's name to the list.
        
        objToCheck.children.forEach(function(child){
            resolveCircularDependency(stack, objToCheck, child);//recursively checks all children for circular dependencies.
        })
    }
    else if(foundMatch){
        parent.children = [];
        parent.circular = true;
        stack.pop(objToCheck.name);
        return;
    }
    else{
        return;
    }
}
resolveCircularDependency([],tempObject1, tempObject1) 

This process results in modifying the original object provided.

I hope this solution proves useful!

Answer №2

When troubleshooting, utilize console.table(circularObj) for assistance

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is jQuery $.ajax returning a JSON parsing error even though the JSON request is valid?

Here is a basic ajax call that I am trying to make: $.ajax({ url: 'http://localhost:39657/List/Receptacle', dataType: "json", success: function(json) { alert("success"); } }); After checking in Fiddler, the complete response looks l ...

The browsers Firefox and Internet Explorer are unable to perform ajax requests

Currently, I am utilizing jQuery version 3.3 in conjunction with the following Ajax script: <script type="text/javascript"> $(document).ready(function(){ $("form").submit(function(){ $.ajax({ url: 'msgs.p ...

Tips for validating the presence of an item in your React shopping cart using UseReducer

There was a challenge I faced where I needed to prevent an item from being added twice in my shopping cart. After searching this platform for answers, I came across a question titled Check if item already exists in cart when adding REACT, but unfortunately ...

Transfer data between an HTML page and a PHP page hosted on separate locations using jQuery

Below is the code snippet I am currently working on: function send_data() { var a=$("#username").val(); var b=$("#password").val(); $.post("http://localhost/login/login.php", {uname: a, pswd: b}, function(data) { $("#result").html(data); }); ...

Highlight or unhighlight text using Javascript

Currently, I am facing a challenge in highlighting specific words on an HTML page. Although I have succeeded in highlighting the desired element, I am struggling with unhighlighting the previous word when a new search is conducted. Despite my attempts to i ...

Revise the model and execute the function

When updating my model object, I am looking for a way to trigger a specific method. I have considered options such as: findOne modifying my properties calling the method on the object save Is there a way to achieve this using update or findOneAndUpdate ...

Ways to extract data from an array nested within a JSON object

I am seeking guidance on how to access the value of "result 2" from my JSON object using jQuery or pure JavaScript. var jsonarray = [{ title: "Category1", items: [{ result: "Item1", //Nested array items2: [{ //How to get the value o ...

Encountering numerous errors when attempting to incorporate lottie-web into my JavaScript file

I am in the process of creating a unique audio player for my website utilizing HTML, CSS, and JavaScript. I encountered some challenges while trying to get it to work effectively on Codepen as well as my text editor. The animations were not functioning pro ...

Collecting JSON elements into an array on an Android device

My goal is to extract the URLs that come after "unescapedUrl" and store them in a String array. This JSON data includes multiple image search results with corresponding URLs. {"responseData": {"results":[{"GsearchResultClass":"GimageSearch","width":"1916 ...

Guide to implementing personalized validation for an angular component

In my Angular component, I am looking to implement a custom input validator. However, I am facing an issue while trying to access the ngModelController in the $onInit function. It seems that the form is not populated at this stage. Strangely, in the sendEm ...

Is there a way to programmatically bind a JSON web API to a MySQL database, utilizing any existing solutions

In search of a solution to define GET and POST requests that work with JSON for querying and updating a MySQL database. The backend server handling these interactions will be created in C#. My aim is to utilize a JSON API for CRUD operations and specific ...

Did I incorrectly pass headers in SWR?

After taking a break from coding for some time, I'm back to help a friend with a website creation project. However, diving straight into the work, I've encountered an issue with SWR. Challenge The problem I'm facing is related to sending an ...

What steps should I take to include a Follow - Unfollow Button on my Website?

I need to add a button on my website that allows users to either follow or unfollow a specific game. Here is the table for the follow buttons: Follow Button Table When a user clicks on the button related to the game ID, it should update the game_follow d ...

Rails not recognizing Bower components

I have integrated angular and bootstrap into my Rails application using bower, but the JavaScript is not rendering properly. Both CSS and Java Script are not functioning Here is the code snippet: vendor\assets\javascript\application.js / ...

Retain the jQuery dropdown menu in an open state while navigating to a different webpage on the

I am encountering an issue with a drop-down menu on my website. Whenever I click on a submenu link, the new page opens but the menu automatically closes. However, I want the active menu to remain open even on the new page. To solve this problem, I believe ...

Seeking out an item using anchor text: The ultimate guide

Here is a collection of various links to choose from: <a href="/111">AAAAA</a> <a href="/222">BBBBB</a> <a href="/333">CCCCC</a> I am interested in selecting the link with the text BBBBB and then applying the following ...

Tips for updating or toggling an icon within a button with the help of Bootstrap 5 and jQuery

Looking to switch the icon displayed inside a button upon clicking? The initial icon is <i class="fas fa-bars"></i>, and after being clicked, it should change to <i class="fas fa-times"></i>. How can this be ach ...

Understanding the process of interpreting the DateTimeOffset data that has been serialized by DataContractJsonSerializer

After serializing an object with the current date in DateTimeOffset using DataContractJsonSerializer, the output appears as follows: <root type="object"> <blah type="object"> <DateTime>/Date(1315565372414)/</DateTime> <OffsetMin ...

Exploring Globalization in NextJS

As I work on setting up a NextJS project that requires i18n support, I have come across various libraries dedicated to internationalization. Are these libraries truly necessary? After reviewing the documentation, I find the idea of keeping an object at a g ...

Methods for showcasing Array values by utilizing a timeout function

In the array below, I have a list of values: var pages = [{“page”:”url1”,”time”:”20”}, {"page":"url2”,”time”:”25”}, {"page":"url3”,”time”:”10”}, {"page":"url4”,,”time”:”12”}, {"page":"url5”, ...