What is the correct way to utilize a recursive function call in order to retrieve the property of a deeply nested object?

In my Angular project, I am incorporating the AngularTree directive from to display a tree view based on this specific data structure:

$scope.subjectAreas = [
        {
            name:   "Area-1",
            link:   "dashboards.dashboard_1",
            entities: [
                {
                    name: "entity 1"
                },
                {
                    name: "entity 2"
                }
            ]
        },
        {
            name:   "Area-2",
            link:   "dashboards.dashboard_1",
            entities: [
                {
                    name: "entity 3"
                }
            ]
        },
        {
            name:   "Area-3",
            link:   "dashboards.dashboard_1",
            entities: [
                {
                    name: "entity 4"
                },
                {
                    name: "entity 5"
                },
                {
                    name: "entity 6"
                }
            ]
        }
    ];

The treeView directive includes a helpful "createSubTree" function that I am utilizing in the following manner:

function createSubTree(level, width, prefix) {
        if (level > 0) {
            var res = [];
            for (var i=1; i <= width; i++)
                res.push({ "label" : getName(i), "id" : "id"+prefix + i, "i": i,
                    "children": createSubTree(level-1, setNumberOfChildren(getName(i),i), prefix + i +".")});
            return res;
        }
        else
            return [];
    }

These are the supporting functions used in my implementation:

function countNumberOfEntities(index){

        return $scope.subjectAreas[index].entities.length;
    }

    function getSubjectAreasLength(){
        return $scope.subjectAreas.length;
    }

    function setNumberOfChildren(subjectArea, index){
        var numberOfChildEntities = countNumberOfEntities(index-1);
        return numberOfChildEntities;
    }

    function getName(index){
        if($scope.subjectAreas[index-1]){
            var subjectAreaName = $scope.subjectAreas[index-1].name;
            var n = subjectAreaName;
            return subjectAreaName;
        }
    }

While the tree view displays correctly, all children (entities within each SubjectArea) are displaying the same names as their parent SubjectArea.

The current output is shown below:

Area-1
   Area-1
   Area-2
Area-2
   Area-1
Area-3
   Area-1
   Area-2
   Area-3

The desired output should be like this:

Area-1
   Entity-1
   Entity-2
Area-2
   Entity-3
Area-3
   Entity-4
   Entity-5
   Entity-6

To achieve this result, how can I modify the "createSubTree" function to ensure each entity's name is displayed correctly when called recursively here:

"children": createSubTree(level-1, setNumberOfChildren(getName(i),i), prefix + i +".")});

Answer №1

Revise your code like this:

function generateSubTree(arr) {
    var result = [];
    if (arr) {
        result = arr.map(function(value, key) {
            var id = key + 1;
            return {
                index: id,
                identifier: 'id' + id,
                title: value.name,
                descendants: generateSubTree(value.entities)
            }
        });

    }
    return result;
}

$scope.treeData = generateSubTree($scope.subjectAreas);

Try to minimize passing indexes and other unnecessary data when working with recursion. While sometimes it may be unavoidable, in this scenario, you can simply pass the main array and recursively process each element's child array without the need for indexes.

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

Fixed: Transmitting user's verified email from website to chrome extension

I am currently in the process of developing a website named websiteA using Laravel 8 and Vuejs, along with a Chrome extension that utilizes JavaScript for web scraping. This extension is designed to extract content from another websiteB, and my goal is to ...

What is the best way to upgrade Angular from version 10 to 12?

Currently tackling an Angular project migration from version 10 to version 12. Unfortunately, the project seems to be encountering issues post-migration and is not running as expected. ...

Combining two sets of elements in Java to form a Json using Jackson

Is there a way to combine two List of objects retrieved from the database into a single object in order to serialize with Jackson and deserialize in the view? ObjectMapper mapper = new ObjectMapper(); jsonTutorias = mapper.writeValueAsString(tuto ...

Placing <object> within the existing HTML form

If a user enters the values 12345 into an input box on my webpage and clicks a button, an object will appear below or instead of the form. The code I have for this functionality is: <form name="form" action="" method="post"> <input type="text" ...

One-stop Java solution for Client-Server Desktop Applications

Considerations are being made regarding the optimal approach to develop a standalone client-server application in Java that includes the following components: Server: The server should offer APIs, potentially using the REST architecture. Client: Utiliz ...

Animate specifically new items in a list rendered via ngFor in Angular animation

I am working with a list of array items in an ngFor loop. I have a basic button that adds an item to the array. My goal is to apply an animation only to the newly added items, but currently all the existing list items also receive the animation upon page l ...

How to display an unordered list horizontally in HTML

I'm working on a screen that has filters displayed vertically, but I want to align them horizontally and have the filter options arranged in two columns. I've tried using CSS properties like spacing, clear, and display block, but the checkboxes/l ...

Changing the absolute layout to utilize floats

I am seeking guidance on a project I am currently working on and would greatly appreciate any help. Main Goal: The objective is to create a drag and drop CMS that allows users to draw elements on a grid and rearrange them as needed. The system will recor ...

What could be causing the issue with res.clearCookie() not functioning properly post deployment on Vercel?

Initially, the application functions flawlessly on localhost. However, upon deployment to Vercel, an issue arises when users attempt to log out and the cookies are not clearing as intended with res.clearCookie(). Consequently, even after a page refresh, t ...

Side menu in Ionic - showing different links depending on whether the user is authenticated or not

I am working on an Ionic app with a side menu that is used for multiple pages. I want to customize the links in the side menu depending on whether the user is authenticated or not. This is how I have set up my routes: module.export = angular.module(' ...

How can I use JavaScript to convert a JSON object into an array for iteration with ng-repeat?

Upon retrieving my JSON object from Firebase, I am faced with the challenge of converting a list into an array for binding in HTML using ng-repeat. The structure of my JSON object is as follows: { "cats1": { "Name": "cricket", "imgUrl": "some ...

The input type file is not correctly inserting an image into the image tag

While I was working on a project, I had a question that got answered but now I need to find a different way to use the solution. I have created a jsFiddle to demonstrate how it currently works. You can view it here: http://jsfiddle.net/TbZzH/4/ However, w ...

Effortless jQuery Parallax

Seeking assistance with debugging this jQuery code that manipulates the top margin of an element within a container. The container has a fixed size and overflow set to hidden to create a parallax effect. The parallax effect is functioning properly, but it ...

perform asynchronous calls within a for loop in a synchronous manner

Having issues with managing asynchronous events in sails.js. Obtaining data from a JSONapi and attempting to insert it into the database sequentially within a for loop. The goal is to maintain the correct order of execution. For simplicity, consider the f ...

Using HapiJs in Node.js to communicate data back and forth with the client

I have client.js and server.js files that are used to send data to my server using ajax. I am able to successfully send the searched username, but on the server side, the domain is being received as undefined. I'm unsure if the issue lies on the clien ...

Clicking on the input element in an md-checkbox will toggle the checkbox option

I have a unique feature in my list of checkboxes where users can select an "other" option and input their own text. Here is how it works: <md-checkbox class="md-checkbox-interactive" ng-model="$ctrl.someVar"> <input type="text" placeholder="Pla ...

What is the reason for the inability to input a null byte in a file when using ascii mode with node.js?

Below is the code snippet I have written: var fs = require('fs'); var fp = fs.openSync('binary.txt', "w"); var byte = '\0'; fs.writeSync(fp, byte, null, 'ascii'); However, upon execution, when I check the con ...

Are there any methods for simultaneously hosting both React and vanilla JavaScript websites?

I want to host a full-fledged web application that is primarily implementing ReactJS, but also contains sections utilizing vanilla JavaScript. Is it possible to host a web app that combines both React and vanilla JavaScript functionalities? (My backend i ...

Strange rendering in CSS JQuery Datatable

I am encountering an issue with a DataTable from datatables.net. Each row can be selected by clicking on a checkbox, which triggers a click event. In response to the event, I add or remove a CSS class to change the appearance of the selected rows. $(".cbD ...

Another drop-down is hiding the bootstrap-select drop-down from view

What could be causing some parts of the first drop-down menu to be hidden by another drop-down menu below in the code snippet provided? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv= ...