`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

The MongoDB GridFS is refusing to accept the buffer being written

Hey everyone, I've been working on this issue for nearly a day now and can't seem to figure it out. I'm utilizing multer's inMemory flag to upload an image from my website. My approach involves writing the buffer received from multer to ...

Is there a way to retrieve localStorage setItem after an hour has passed?

When the user clicks on the close icon, the notification screen disappears. How can I display the same screen to the user again after an hour? Please provide guidance. const [hideLearningMaterialClosed, setHideLearningMaterialClosed] = useState(false) ...

What is the CSS/HTML code to position text at the bottom of an image overlay in a card design?

I've been attempting to modify the justify-content in the CSS class to "flex-end" and "end," however the text is not relocating to the bottom. My suggestion is that we concentrate on the img-overlay class, as that's where we adjust the position ...

Determining the distance between two points in miles using Next.js

Are you familiar with the concept of geographical coordinates? Take for example these two points: point1 = {lat: 40.6974034, lng: -74.1197636} point2 = {lat: 42.694034, lng: -75.117636} My goal is to find the distance between these two poi ...

The resolve in Angular UI-Router is not being properly injected into the controller

As a Java developer venturing into the world of Angular and Express, I am encountering challenges along the way. To gain hands-on experience, I am attempting to create a small application using these technologies. The Goal: I have provided a password rese ...

Strange Firefox behavior with absolutely positioned div and percentage height

One of my projects includes a CSS modal dialog that is structured as follows div { position:fixed; top:50%; left:50%; margin:-26% 0 0 -26%; width:46%; height:46%; padding:3%; } Interestingly, this div appears centered in webkit browsers. Ho ...

Tips on utilizing CSS modules in React without changing class names

After starting to use css modules in my react project, I quickly realized the struggle of changing classnames to fit the requirements of css modules. For example, if we have a component using regular css: import React from 'react' import ". ...

Is there a way to achieve a double background color effect in CSS while ensuring that the text is centered within the second background color element?

How can I achieve a layout similar to the one shown in this image: ul menu li tags Should I use two tags for each element? Here is an example: <ul class="menu"> <div class="outside"><li class="inside"><a href="#">Firefox</a ...

Newbie to Next-JS exploring the use of two dynamic APIs, with successful integration of one while encountering difficulties with the other

I recently received help from a friend to transform my inefficient JS web app into a next-app. However, as I attempted to progress further, I encountered various obstacles and found myself feeling lost. Within my project, I have developed two APIs that fe ...

Do escape sequences in JSON get escaped in a sequential or simultaneous manner?

Picture this: I need to store the literal string "\u" in a JSON string. This article offers a helpful visual guide to escape sequences in JSON, but it's not clear whether they are escaped simultaneously or in a specific order. Let's examin ...

Is there a way to arrange the outcomes in a single line?

I need help displaying my results in three rows side by side in React/JavaScript using flexbox. Since I only have one CardItem, I can't just copy and paste it three times as it would show the same result in each row. Is there a way to achieve this wit ...

Can you provide the specific URL for a Metacafe video to stream within a div container?

Could anyone assist me in finding the "Direct Url" to play metacafe videos within a div element? ...

Validating complex ASP.NET MVC objects using AngularJS

I am encountering an issue with validating my model in a subform using AngularJS. Despite making changes to the SearchPostCode values and seeing updates in classes, the error message fails to display, and the button remains disabled. <form novalidate&g ...

What is the best way to name a force-directed Graph using d3?

I'm struggling to label the nodes in my force-directed graph created with d3.js. Despite trying various solutions from StackOverflow and online tutorials, I believe my issues stem from a lack of fundamental understanding of JavaScript. I've expe ...

Struggling to understand the concept of utilizing Promises for data retrieval

I'm currently facing an issue with my async function that awaits a GraphQL call. Even though the call returns a Promise containing the desired data, I'm struggling to access it effectively. Below is the snippet of code in question: export async ...

Can you provide guidance on how to prioritize container div style over CSS class?

Here's the HTML code snippet I'm working with: <html> <head> <style> .text-box { color: red; } </style> </head> <body> <p class=&qu ...

Struggling with a 400 Bad Request Error in Angular with WebAPI Integration

I've been working on creating a database to keep track of comics, and so far I can successfully add new comics and retrieve them using GET requests. However, I've hit a roadblock when trying to update existing comics using PUT requests. Every tim ...

Extracting information from CSS code

I am struggling to parse a RSS feed because all the information is contained within the description element. The CSS formatting makes it challenging to extract the actual strings. For example, below is a snippet of the description element: <table style ...

Building a GWT webpage from scratch: A step-by-step guide

My project involves creating a website that features various Java tasks and informational content. Users can navigate through different pages by clicking on links from the homepage. Specifically, on the Java page, users will be able to complete tasks. Th ...

Assign a value of an empty string to the attribute

My goal is to use jQuery to toggle the required attribute on fields. Initially, on page load, I add the required attribute to the necessary elements like this: $("[data-required]").attr("required", ""); Then, I have a toggle ...