Simplified JavaScript Object Structure

A JSON array that is flat in structure looks like this:

var flatObject = 
[
    { id : "1", parentId : "0", name : "object 1" },
    { id : "2", parentId : "1", name : "object 2" },
    { id : "3", parentId : "2", name : "object 3" },
    { id : "4", parentId : "3", name : "object 4" },
    { id : "5", parentId : "4", name : "object 5" },
    { id : "6", parentId : "5", name : "object 6" },
    { id : "7", parentId : "1", name : "object 7" },
    { id : "8", parentId : "1", name : "object 8" },
    { id : "9", parentId : "1", name : "object 9" }
];

To display a hierarchy based on an ID by traversing through parent IDs, we need to simplify the existing code. Although I know the depth is fixed at 5 levels, the current function has a lot of redundant lines. Let's consider using recursion for a more concise solution. Here is the original function:

function getItems(id){

    if(!id){
        document.getElementById("demo").innerHTML = "";
        id = document.getElementById("hvitems").value;
    }

    for(a=0;a<flatObject.length;a++){

        var objA = flatObject[a];
        var objIdA = objA.id;

        if(objIdA == id){

            var objNameA = objA.name;

            document.getElementById("demo").innerHTML += "(" + objIdA + ") " + objNameA + "<br>";

            // look for parentIds matching the current Id
            for(b=0;b<flatObject.length;b++){

                var objB = flatObject[b];
                var objIdB = objB.id;
                var objParentIdB = objB.parentId;

                if(objParentIdB == objIdA){

                    var objNameB = objB.name;

                    document.getElementById("demo").innerHTML += " - (" + objIdB + ") " + objNameB + "<br>";

                    // recursively search for parentIds
                    for(c=0;c<flatObject.length;c++){

                        var objC = flatObject[c];
                        var objIdC = objC.id;
                        var objParentIdC = objC.parentId;

                        if(objParentIdC == objIdB){

                            var objNameC = objC.name;

                            document.getElementById("demo").innerHTML += " -- (" + objIdC + ") " + objNameC + "<br>";

                            // continue searching for parentIds

                        }

                    }

                }

            }

        }

    }

}

getItems(1);
// or getItems(3); ...

The hierarchical output can be observed within this div:

<div id="demo"></div>

Although functional, there may be room for improvement in terms of efficiency and readability. Learning and utilizing recursion could greatly optimize this process.

To view the full example, check out the live demo.

Answer №1

Avoid using multiple nested loops by utilizing the concept of recursion.

Here's how the algorithm can be implemented:

  • For each index id:
    • Locate the item with the specified id and display its information
    • Identify all items with a parentid that matches the current id, then recursively perform these actions with their respective id values

The implementation is straightforward:

function getItems(id, indent) {
    var current = flatObj.filter(function(x) { 
        return (x.id == id); 
    })[0];

    document.body.innerHTML += indent + " (" + current.id + ") " + current.name + "<br>"; 

    flatObj.forEach(function(x) {        
        if (x.parentid == id) { 
            getItems(x.id, indent + '-'); 
        }
    });
}

getItems(id, '');

The indent parameter is initially an empty string and increments by one - on each recursive call.

You can view a functional example in this JSFiddle link.

Keep in mind that this algorithm assumes a valid input as a tree structure. It does not include checks for loops or parent nodes validity. You may add them based on your requirements.

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

Implement a callback function to dynamically generate variables and display them within an HTML element

Apologies in advance for any errors I may make as I am a beginner when it comes to javascript, jquery, and json. I have a script that retrieves data from a json file and displays it on a webpage using javascript, jquery, ajax (I believe), and json. When ...

Setting response query correctly in Solr using AJAX

Inspired by an example of using Solr's JSON output for AJAX, I have incorporated a drop-down menu into my project form and introduced faceting to the parameters. Parameters: function getstandardargs() { var params = [ 'wt=json' ...

Checking the conditional styling implemented with Material UI makeStyles: a step-by-step guide

For the past few weeks, I've been working on a React app where I heavily rely on Material UI components. One particular component changes its style based on the values of its props. To achieve this, I used the following approach: const useStyles = ...

What is the best way to attach 'this' to an object using an arrow function?

Consider having an object named profile which consists of properties name and a method called getName (implemented as an arrow function). profile = { name: 'abcd', getName: () => { console.log(this.name); } } I am interes ...

Using Jquery to add new HTML content and assign an ID to a variable

Here is some javascript code that I am having trouble with: var newAmount = parseInt(amount) var price = data[0]['Product']['pris']; var id = data[0]['Product']['id']; var dat ...

What is the best way to retrieve the latest files from a Heroku application?

Having recently migrated my Discord Bot to Heroku, I faced a challenge with retrieving an updated file essential for code updates. I attempted using both the Git clone command and the Heroku slugs:download command with no success in obtaining the necessar ...

Vue JS Image Path

I have a Vue.js structure file that looks like this: --assets ----image ------my-image.png ------my-image2.png --components ----user ------userStart.vue To display the images using an array object, my code in userStart.vue is as follows: ...

Laravel validation successfully validates Vanilla AJAX request, but the controller does not receive the values

Currently, I am utilizing AJAX (vanilla JS) to send a form to a Laravel 5.5 controller for searching the Amazon products API. The AJAX is sending the correct keywords and category inputs, but the controller is not receiving them. Even though the request p ...

Determine the precise x and y coordinates of a centered element using JQuery

How can I determine the exact left and top positions of an element? The parent container has text-align: center, causing potential confusion when there are multiple elements on the bottom row. For instance, the first one may have a position of 0px instea ...

Experiencing difficulties extracting data from JSON with python due to receiving a TypeError. Seeking assistance

Here is an example of the JSON data that I am fetching from a URL: [ { "externalModelId": "500A000000RQOwnIAH", "resource": { "account": { "externalModelId": "001A000001EucpoIAB", "resource": { "ac ...

The tableView is not showing the data I have inputted

I am struggling to retrieve data from an API and facing issues with displaying the data. Alamofire.request(https://jsonplaceholder.typicode.com/comments, method: .get, encoding: URLEncoding.default, headers: nil).validate(statusCode: 200..<300).respons ...

Modify mouse pointer when an object is clicked using JavaScript

Greetings, I am in the process of designing a website for a client. I have encountered a challenge in changing the cursor icon when a user performs a mousedown on an object. There is an image on the webpage When the user clicks on the image, the cursor s ...

Utilizing Shadow Root and Native Web Components for Seamless In-Page Linking

An illustration of this issue is the <foot-note> custom web component that was developed for my new website, fanaro.io. Normally, in-page linking involves assigning an id to a specific element and then using an <a> with href="#id_name&quo ...

In JavaScript, how can we determine the structure of an object similar to the str function in R language?

One of the great features in R is the use of the str function, which allows you to examine the structure of an object. For example, you can use it to analyze the structure of a parsed json object like this (I'm using json as an illustration): txt = ...

Obtain the numerical value of the vertical position of the mouse (

Currently, I am coding a JavaScript game and my objective is to designate a variable specifically for the Y axis of the mouse. I kindly request that the code be kept as simple and straightforward as possible, avoiding unnecessary complexity. That conclud ...

Choose a random element from a string with Javascript

Could someone please help me figure out why my code isn't functioning as expected? I'm trying to randomly select three names from a list and ensure that no name is repeated. While I believe I am on the right track, something seems to be missing. ...

Updating with MySQL can only manipulate integers and not strings

Setting up seems simple, but the number of potential causes is overwhelming for someone new to programming like me: In JavaScript, I define and later call: function dbUpdate(x, y, z) { $.ajax({ url: 'php/dbUpdate.php', type: ...

Command to conceal components for users visiting as guests

I'm looking to develop a directive that hides specific elements for guest users. Here is the current code I have: angular.module('someMod') .directive('premiumUser', premiumUser) .controller('PremiumUserCtrl', Pr ...

Failure of window marker to trigger click event in jquery-bing-maps

I'm encountering an issue where clicking on links within Window markers on Bing Maps redirects me to a new page instead of triggering a JavaScript event as intended. $('.single_address').on('click', function (evt) { alert(&apo ...

Validating checkboxes in a jQuery DataTable using JavaScript

I am working with a table that is connected to a JQuery datatable. <table id="grid1"> <thead> <tr> <th>Name</th> <th>View</th> <th>Modify</th> </tr> </thead> </ta ...