`Turn nested JSON into a formatted list using jquery`

I am currently facing two challenges:

  1. I am having trouble with the HTML structure, as shown in the image below

Current HTML structure: https://i.stack.imgur.com/GH46J.png

Desired HTML structure:

https://i.stack.imgur.com/Dq3Gn.png

  1. How can I create dynamic JSON code that supports multiple levels of sub-menus without writing excessive loops and conditions?

Here is a snippet of the code I have been working on:

$(document).ready(function(){

 var treeJson = {"values":[
        // JSON data here...
    ]};
var treeParentArr = treeJson.values;
if(treeParentArr.length){
    var $ulLevel1 = $("<ul />").appendTo($("#tree"));
    // code logic for rendering dynamic JSON goes here...
}
});

JSFiddle link:

Click here to view JSFiddle

Answer №1

Are you seeking this information?

$(document).ready(function() {

    var treeJson = {
        "values": [{
                "tree_title": "FashionWorld1",
                "tree_image": "img_arrow",
                "tree_image_position": "1",
                "tree_image": "FashionWorld",
                "isopen": "0",
                "child": [{
                    "values": [{
                            "tree_title": "SubmenuLevel11",
                            "tree_image": "img_arrow",
                            "tree_image_position": "1",
                            "tree_image": "FashionWorld",
                            "isopen": "0",
                            "child": [{
                                "values": [{
                                        "tree_title": "SubmenuLevel21"
                                    },
                                    {
                                        "tree_title": "SubmenuLevel22"
                                    },
                                    {
                                        "tree_title": "SubmenuLevel23"
                                    }
                                ]
                            }]
                        },
                        {
                            "tree_title": "SubmenuLevel12"
                        },
                        {
                            "tree_title": "SubmenuLevel13"
                        }
                    ]
                }]
            },
            {
                "tree_title": "FashionWorld2",
                "tree_image": "img_arrow",
                "tree_image_position": "1",
                "tree_image": "FashionWorld",
                "isopen": "0",
                "child": [{
                    "values": [{
                            "tree_title": "SubmenuLevel11",
                            "tree_image": "img_arrow",
                            "tree_image_position": "1",
                            "tree_image": "FashionWorld",
                            "isopen": "0",
                            "child": [{
                                "values": [{
                                        "tree_title": "SubmenuLevel21"
                                    },
                                    {
                                        "tree_title": "SubmenuLevel22"
                                    },
                                    {
                                        "tree_title": "SubmenuLevel23"
                                    }
                                ]
                            }]
                        },
                        {
                            "tree_title": "SubmenuLevel12"
                        },
                        {
                            "tree_title": "SubmenuLevel13"
                        }
                    ]
                }]
            },
            {
                "tree_title": "FashionWorld3",
                "tree_image": "img_arrow",
                "tree_image_position": "1",
                "tree_image": "FashionWorld",
                "isopen": "0",
                "child": [{
                    "values": [{
                            "tree_title": "SubmenuLevel11",
                            "tree_image": "img_arrow",
                            "tree_image_position": "1",
                            "tree_image": "FashionWorld",
                            "isopen": "0",
                            "child": [{
                                "values": [{
                                        "tree_title": "SubmenuLevel21"
                                    },
                                    {
                                        "tree_title": "SubmenuLevel22"
                                    },
                                    {
                                        "tree_title": "SubmenuLevel23"
                                    }
                                ]
                            }]
                        },
                        {
                            "tree_title": "SubmenuLevel12"
                        },
                        {
                            "tree_title": "SubmenuLevel13"
                        }
                    ]
                }]
            },
            {
                "tree_title": "FashionWorld4",
                "tree_image": "img_arrow",
                "tree_image_position": "1",
                "tree_image": "FashionWorld",
                "isopen": "0",
                "child": [{
                    "values": [{
                            "tree_title": "SubmenuLevel11",
                            "tree_image": "img_arrow",
                            "tree_image_position": "1",
                            "tree_image": "FashionWorld",
                            "isopen": "0",
                            "child": [{
                                "values": [{
                                        "tree_title": "SubmenuLevel21"
                                    },
                                    {
                                        "tree_title": "SubmenuLevel22"
                                    },
                                    {
                                        "tree_title": "SubmenuLevel23"
                                    }
                                ]
                            }]
                        },
                        {
                            "tree_title": "SubmenuLevel12"
                        },
                        {
                            "tree_title": "SubmenuLevel13"
                        }
                    ]
                }]
            }
        ]
    };
    var treeParentArr = treeJson.values;
    var tree = buildNodes(treeJson, $("#tree"));
});

function buildNodes(node, parent) {
    $(node.values).each(function() {
        var element = this;
        var listItem = $("<li />", {
            text: this.tree_title
        })
        if (this.hasOwnProperty("child")) {
            var tree = $("<ul />");
            buildNodes(this.child[0], tree);
            listItem.append(tree)
        }
        parent.append(listItem);
    });
}

JSFiddle

Just wondering, why have the nested values inside child when it's an Array and could be named something like childs for the values objects?

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

Exploring the properties of individual Vue components on a single page with v-for loop

Struggling to render a Vue component in a Rails app by iterating through an array of data fetched via Ajax. The Slim template (index.html.slim) for the index page includes a custom_form_item component, where items represent custom forms data from Rails and ...

Utilizing jQuery's .clone() function to duplicate HTML forms with radio buttons will maintain the radio events specific to each cloned element

I'm currently developing front-end forms using Bootstrap, jQuery, HTML, and a Django backend. In one part of the form, users need to input "Software" information and then have the option to upload the software file or provide a URL link to their hoste ...

Tables lacking borders where rowspans are present

I'm currently using Firefox and have the following code snippet: html, body { width: 100%; height: 100%; } * { box-sizing: border-box; } body { padding-left: 20px; padding-right: 20px; } .visitentabelle { border: 2px solid black; ...

Fetching data in React using AJAX

I am in the process of developing a React Component that will display data retrieved from an AJAX call. Here's my scenario - I have a Jinja Flask back end hosted on AWS API Gateway, which requires custom headers and the Authorization header to serve H ...

The Proper Method of Displaying Data from a JSON File Using AngularJS

I'm having trouble getting the data from a JSON file (click on the "Json File" link to view the structure). I'm not sure what to put after "$Scope.listOfRecipe=". I tried using response.data.recipes, but it's not working and causing errors. ...

How to keep jQuery horizontal submenu open when clicking on the menu

Seeking assistance with a menu issue. I have a horizontal menu with subitems that display when clicked, but having trouble with the submenu behavior. When clicking on a submenu item, I want it to remain open and show the related items underneath it. For ex ...

Customizing Carousel Arrows in Angular with ng-bootstrap

I need help changing the position and icon of control arrows using Bootstrap. I've tried targeting "carousel-control-prev-icon" & "carousel-control-next-icon", but nothing seems to work. Any suggestions on how to properly solve this issue? Here is th ...

Bootstrap 3 offset doesn't respond to dimensions

Even though I have set an offset for a medium-sized screen, the offset still appears in large screens. Here is a snippet of my HTML code. How can I resolve this issue? <div class="col-lg-6 col-sm-12"> <div class="row"> <div class="co ...

Tips on fetching the ID of the selected option using JavaScript without relying on jQuery

Looking to print the selected option ID using pure Javascript (not JQuery) for multiple select tags. If we have more than one select tag, how do we achieve this? <select onchange="showOptions(this)" id="my_select1"> <option value="a1" id="ida ...

Vuetify ensures that elements remain in a single row and adjust their size according to the content

I'm trying to create a layout with a single row that has a button aligned to the right edge, and the rest of the space filled with multiple buttons inside a v-chip-group. There are more buttons than can fit in the available space, so I want the v-chip ...

Is there a way to program custom key assignments for my calculator using JavaScript?

As a beginner in the world of coding and JavaScript, I decided to challenge myself by creating a calculator. It's been going smoothly up until this point: My inquiry is centered around incorporating keys into my calculator functionality. Currently, th ...

The syntax for importing JSON in JavaScript ES6 is incredibly straightforward and

Whenever I attempt to write my code following the ES6 standard and try to import a .json file, it ends up failing on me. import JsonT from "../../Data/t.json" //not functioning as expected var JsonT = require('../../Data/t.json'); //works fine ...

URL Labeler StateProvider: A unique StateProvider that adds a distinctive label to the

I need help figuring out how to add a user-friendly URL at the end of the current URL using $stateProvider. As an example, on StackOverflow's question pages, the URL format is stackoverflow.com/questions/(question_id)/(question title). I want to repl ...

Alter the style type of a Next.js element dynamically

I am currently working on dynamically changing the color of an element based on the result of a function //Sample function if ("123".includes("5")) { color = "boldOrange" } else { let color = "boldGreen" } Within my CSS, I have two clas ...

Tips for utilizing flexbox and React-Native to ensure a cropped image takes up the entire View

I'm trying to create a cropped image that fills the entire screen in my app. Currently, my code looks like this: https://i.stack.imgur.com/9DtAc.png However, I want the small square of Homer eating donuts to occupy the entire screen, similar to the ...

Creating an array with conditional elements in React involves utilizing the map method along with a conditional

My array, named tableFilterFields, looks something like this: const tableFilterFields = [ { label: "Start Date", name: "StartDate", type: FilterControls.DatePicker, defaultValue: new Date(new Date().setDate( ...

Successful Mongoose query in Node.js, however the array remains empty even after using forEach loop. Issue with MongoDB integration

After performing a forEach inside an asynchronous method, I am trying to return an array of names. The issue is that despite the forEach working correctly, the array always ends up empty. On the website side, here is my request: function retrieveCharity( ...

What is the best way to save javascript code without running it?

I've been attempting to insert AdSense JavaScript code into a specific div location using jQuery, but it appears that the JavaScript code does not function well inside a jQuery variable. It gets executed instead. Despite trying to encode it with PHP&a ...

Using Next-auth.js: Redirecting from getServerSideProps to a specific callback URL - How can it be done?

Hey, I've been working on implementing authentication with the NextAuth library in my Next.js application. While following the documentation, I encountered a situation that wasn't covered. I'm attempting to create a 'route guard' o ...

Exploring the functionality of Rails 5.1 API in combination with VueJS2

I have integrated Vue.js into my existing Rails app, which includes a resource that renders JSON data. I used Postman to verify the JSON data and it seems to be working correctly. To set up Vue.js, I added the webpacker gem to my Gemfile: gem 'webpa ...