Ways to organize a highly nested object structure

I have an object structured like this:

var list = [
    {
        category:'CATEGORY 1',
        label:'Item 1',
        children:[{
            category:'CATEGORY 2',
            label:'Item 1',
            children:[]
        },{
            category:'CATEGORY 2',
            label:'Item 2',
            children:[{
                category:'CATEGORY 3',
                label:'Item 1',
                children:[]
            },{
                category:'CATEGORY 3',
                label:'Item 2',
                children:[]
            }]
        }]
    },
    {
        category:'CATEGORY 1',
        label:'Item 2',
        children:[{
            category:'CATEGORY 2',
            label:'Item 3',
            children:[]
        },{
            category:'CATEGORY 2',
            label:'Item 4',
            children:[{
                category:'CATEGORY 3',
                label:'Item 2',
                children:[]
            },{
                category:'CATEGORY 3',
                label:'Item 3',
                children:[]
            }]
        }]
    }
    ]

I need to display the object structure in a view.

https://i.sstatic.net/LyPdy.png

The JSON data is nested deep with multiple layers, possibly 6 to 8 children in each node. I am struggling to figure out how to achieve this using JavaScript.

Should I separate each category and iterate through each object individually?

Answer №1

If you're stuck and in need of some help, a recursive function might just do the trick. Check out this snippet below:

function discoverCategories(list) {
  list.forEach(function(item) {
    // handle category and label here
    console.log(item.category);

    // are there any children in this object? if so, call discoverCategories again
    if (item.hasOwnProperty("children")) {
      discoverCategories(item.children);
    }
  })
}

This function will iterate through all your categories and check for a children property. If found, it will recursively call the discoverCategories() function with the children array to perform the same action.

You can run a live demonstration using the code snippet provided below.

var content = [
    {
        category:'CATEGORY A',
        label:'Item X',
        children:[{
            category:'CATEGORY B',
            label:'Item Y',
            children:[]
        },{
            category:'CATEGORY B',
            label:'Item Z',
            children:[{
                category:'CATEGORY C',
                label:'Item Y',
                children:[]
            },{
                category:'CATEGORY C',
                label:'Item Z',
                children:[]
            }]
        }]
    },
    {
        category:'CATEGORY A',
        label:'Item Y',
        children:[{
            category:'CATEGORY B',
            label:'Item Z',
            children:[]
        },{
            category:'CATEGORY B',
            label:'Item W',
            children:[{
                category:'CATEGORY C',
                label:'Item Z',
                children:[]
            },{
                category:'CATEGORY C',
                label:'Item X',
                children:[]
            }]
        }]
    }
    ]

function discoverCategories(list) {
  list.forEach(function(item) {
    // handle category and label here
    console.log(item.category);

    // are there any children in this object? if yes, call find categories again
    if (item.hasOwnProperty("children")) {
      discoverCategories(item.children);
    }
  })
}

discoverCategories(content)

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

Tips for correctly annotating the jersey method to accept JSON data

I am facing an issue with the jersey method declaration below: @POST @Path("/fooPath") @Produces({MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_JSON}) public Response isSellableOnline(@FormParam("productCodes") final Li ...

New inputs cannot be accepted by the form

HTML <form action="./Login.php" method="post" onsubmit="return checkInput();"> <table width="300" border="1"> <tbody> <tr> <th> UserName: </th> <td><input class="box" type="text" value="" name="uname" id="uname ...

Working with JSON Serialization in the .NET Framework

Recently, I developed a basic web service using .net for mobile app integration. Although the service currently outputs Json, the structure is not exactly what I require. Here are the models I have created: [DataContract] class PoiList { [DataMember] ...

The performance of Javascript code comes to a screeching halt

I recently developed a JavaScript script to convert over 300 images to base-64 format. <script type="text/javascript"> var parts, images; var canvas=document.getElementById("myCanvas"); var container = $("#container ul"); ...

What are the steps to ensure a successful deeplink integration on iOS with Ionic?

Recently, I was working on a hybrid mobile app for Android/iOS using Nuxt 3, TypeScript, and Ionic. The main purpose of the app is to serve as an online store. One important feature involves redirecting users to the epay Halyk website during the payment pr ...

swap = with u003d in c sharp

Trying to decode a base-64 string: oKQmwbpPwZGxUGeWQNBucVmNy1JVsxM9uNivn6hpkia+15y3yIemkW8GXW423krf8WNk6yebQixZW78EpPMMtzldQbbsaEmd4aUDCwp78ivOuh83nC8fHy2gwkm5NcS7aaGm2KxkUsWa5ouNUa7BUWPZ3F7LXFR/SLjZRTMY8u7hwYEQCmUQk/zNXsLyHHwZQiOjZfXdb1nC4vu1LItxaw== Tri ...

JavaScript technique for dynamically clicking an 'a href link'

Similar Question: Is it possible to simulate a click event on a link or element using JavaScript? How can I programmatically click an anchor (href) link using JavaScript? I have the following code to trigger JavaScript functionality when the link is cl ...

Generating unique IDs for multiple forms with the help of jQuery and PHP

I am facing an issue with multiple forms on my webpage. I submit these forms to the database using AJAX. The problem is that each form requires a unique ID in order to be submitted with AJAX (jQuery id selector), but only the first form gets submitted via ...

tips for choosing a specific dropdown menu item

I'm having an issue with a function that I want to apply to all my dropdown lists. The problem arises when I try to select an option from the second dropdown list - instead of displaying the correct value, it shows the value from the first group in th ...

Combining three APIs within an HTML website

Hey there! Currently, I am in the process of combining three APIs into my HTML website. However, there seems to be an issue where each subsequent API integration overrides the previous one, and only the final one functions properly. In the code snippet b ...

Problem with encoding JSON using file_get_contents

I am facing an issue while trying to parse the content of a .json file into a PHP array. Here is the content of the file: { "questions": "reponse" } Despite my efforts, I am encountering a strange problem. Here is the code snippet I am using: $path = &a ...

Best practices for blocking the interface in AngularJS during data loading phase

Within my form, there are numerous fields where the data is fetched from a server, including dependent data lists. During this data loading process, I would like to freeze the interface by displaying a progress bar. This can be achieved by overlaying a lay ...

JavaScript - utilize regular expressions to check if the argument starts with a forward slash

Currently, I am utilizing nodejs for API testing purposes. To properly test the logic within this if statement, I am in search of a string that aligns with this specific regular expression. if (arg.match(/^\/.*/)) { // ... } Would anyone be able ...

Highcharts JS encountered an error: x[(intermediate value)(intermediate value)(intermediate value)] is not a valid constructor

I'm in the process of creating a bar chart by fetching options from an ajax response. However, I encountered an error when passing the object to the highcharts constructor. Uncaught TypeError: x[(intermediate value)(intermediate value)(intermediate v ...

Struct causing segmentation fault within loop?

I recently had to modify a working program by consolidating four arrays into one. To achieve this, I implemented a typedef struct and defined a data type called "stuff." Subsequently, I created an array of the stuff datatype named "everything," which conta ...

Creating an array from a string delimited by commas in PHP

Here is a sequence of numbers: 37,40,42,46,49,54,56,57. I am looking to separate each number and convert them all into an array format. The desired array would be: array(37,40,42,46,49,54,56,57) ...

"What could be the reason behind the sudden disappearance of the TinyMCE icon in my Vue

Welcome to my unique website design! https://i.sstatic.net/rtEwF.png Check out the special tinymce code I created https://i.sstatic.net/8su0i.png https://i.sstatic.net/9y2AO.png ...

I'm curious to understand the inner workings of how chained functions operate in JavaScript when there is a prototype function included in the chain

Looking to separate the chained calls, starting from: request .post('/upload') .attach('image1', 'path/to/felix.jpeg') .attach('image2', imageBuffer, 'luna.jpeg') .field('caption', 'M ...

Retrieve components of Node.js Express response using axios before terminating with end()

Is there a way to receive parts of a response from my nodejs server before res.end() using axios? Example: Server router.get('/bulkRes', (req,res)=>{ res.write("First"); setTimeout(()=>{ res.end("Done"); },5000); }) Cl ...

Using ajax to send a JSON object to a controller class in a Spring MVC application

I have recently delved into learning spring mvc and decided to practice on my own. However, I encountered an error that has left me puzzled. Can someone please help with the code? When passing a JSON object from my JSP page to the controller class, I rece ...