How can I generate a horizontal navigation bar using a JSON structure?

I have a JSON object that looks like this:

var data = [
        {
        "parent": "Home",
        "child": [

                ]
        },
        {"parent": "Services",
        "child": [
                {"title":"Infrastructure"},
                {"title":"Development"}

                ]
        },
        {
        "parent": "Sector",
        "child": [
                {"title":"Recruitment Consultant"},
                {"title":"Change Management"},
                {"title":"Industrial Relations"}
                ]
        },          
        ]

I am looking to create a horizontal menu based on this JSON structure. Since I am new json objects, can someone guide me on how to achieve this?

Answer №1

To accomplish this task, follow these steps.

Code Explanation

<ul id="nav"></ul>

JavaScript Logic

var data = [
    {
    "parent": "Home",
    "child": [

            ]
    },
    {"parent": "Services",
    "child": [
            {"title":"Infrastruture"},
            {"title":"Development"}

            ]
    },
    {
    "parent": "Sector",
    "child": [
            {"title":"Recruitment Consultant"},
            {"title":"Change Management"},
            {"title":"Industrial Relations"}
            ]
    },          
    ];
$(function() {
    var nav = $("#nav");
    $.each(data,function(idx, obj){
        if(obj.child.length>0)
        {
            nav.append('<li><a href="#">'+obj.parent+'</a><ul id="'+obj.parent+'">'); 
            var parent = $("#"+obj.parent); 

            $.each(obj.child, function(idx, childobj){
                parent.append('<li><a href="#">'+childobj.title+'</a></li>');
            });
            nav.append('</ul></li>'); 
        }
        else
        {
            nav.append('<li><a href="#">'+obj.parent+'</a></li>');
        }
    });
});

This approach may be unconventional due to the mix of markup and JavaScript, but as long as the structure is maintained, it is acceptable.

Check out the live demonstration here

P.S.: The styling aspect is left for you to handle. Consider including classes in your JS along with markup. Enjoy! ;-)

Answer №2

Your JSON data can be manipulated similar to a Javascript Object. Here is an example of how you can interact with it:

for (var i = 0; i < data.length; i++) {

    generateHeaderLink(data[i].parent);
    generateChildLinks(data[i].child);

}

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 <pre> tag is not adjusting the column width properly within the Bootstrap framework

I have utilized Bootstrap CSS to style my webpage. Interestingly, when I incorporate the <pre>...</pre> tag within the class="col", it does not adjust the width of the column as expected, and instead enlarges the entire column's ...

Svelte is unable to bring in

Hey there, I'm new to Svelte and currently working on a simple feedback app. I have divided my project into two files - one for the main app and another for a list of feedbacks. Here is my App.svelte file: <script> import feedback from ". ...

Webpage refreshing when resizing browser

Hey there, I'm facing an issue where my HTML website restarts whenever the browser size changes. Can someone please help me fix this? You can check out my website here I have uploaded my code files here: Code Files Link ...

Using VUE-JS to implement checkbox functionality with v-model

Click here for the image Greetings All, I am new to VUE.JS and seeking assistance. I have checkboxes for MODULES and FUNCTIONS My goal is to add functions for each module that I have. Below is a snippet of my code: <label> Modules:</label> ...

Select the radio button by hovering the mouse over it

Is there a way to check my radio buttons when hovering over them without having to click? I want to display photos based on the selected radio button. I attempted this using JQuery, but I am still learning and consider myself a beginner. ...

Choose options from an array in AngularJS using the same ng-model for a dropdown menu

I have developed a cross-platform app using AngularJS, Monaca, and OnsenUI. Within the app, there is a large form with multiple drop-down select options. The majority of these options are Yes/No selections. To handle these Yes/No options, I've creat ...

Troubleshooting problems in Android with parsing String/JSON data

Just wondering about how to properly parse a JSON string in an Android application. Here's the specific JSON data I'm working with : { "error":504, "result":"[\"USRL3C4NAEL84727\",\"USR1HZE4UN5289H1\",\"USR46476WQB ...

Is it possible to insert JavaScript code with the <link> element?

Is it possible to include JavaScript code using the <link> tag on my website? For instance, if I have a JavaScript file named test.js that includes the simple code alert('hello'); Can I trigger a popup window to appear by using the follow ...

Generating a complex, nested array using dynamic loops from JSON data

Receiving json input is a bit uncertain for me. The number of inputs may vary, and while I know how to turn them into an array, the structure is not what I need. Currently, the array is multidimensional and associative, but it's using 'label&apos ...

Combining AngularJS with Bridgeit.js for a seamless mobile web app experience

Currently, I'm working on an AngularJS web application that requires scanning a package from a mobile device. To achieve this functionality, I am utilizing BridgeIt. Unfortunately, the code I've written in Angular doesn't seem to be functio ...

What is the best way to deploy a Vue Webpack application using Sails.js?

I am currently managing a Sails.js server alongside a Vue Webpack application, running as separate entities. Here's how my folder structure is laid out: /application-root/server/ /application-root/client/ Within the /server/ directory lies my Sails ...

What is the best way to implement window.load in React Native?

I'm encountering an issue with a simple button on my page in Expo/React Native. When I try to navigate to a new page using window.open upon clicking the button, I receive an error message saying "undefined is not a function." Although I am utilizing ...

Transmit information via ajax and receive responses in json format

Looking to send a string and receive JSON format in return. The current method is functional but lacks the ability to return JSON code. $.ajax({ url: "getFeed.php", type: "post", data: myString }); Attempts to retrieve JSON string result in ...

`Div Elements Overlapping`

Lately, I have been working on my personal portfolio and I encountered an issue with the contact form overlapping the footer. Can anyone provide some guidance on how to resolve this? Any help is greatly appreciated. https://i.stack.imgur.com/neIbs.gif ...

What could be causing WidgEditor, the JavaScript text editor, to fail to submit any values?

After clicking submit and attempting to retrieve text from the textarea, I am encountering a problem where the text appears blank. The reason for this issue eludes me. function textSubmit() { var text = $("#noise").val(); console.log(text); consol ...

The problem with the pathLength property is causing my path animation to malfunction

I'm struggling to animate SVG graphics and haven't been able to find much information on this topic online. Recently, I attempted to animate an SVG using framer-motion in a React component. The animation configuration I used is as follows: const ...

Leverage object properties as data table field values in VueJS

In my current project, I am utilizing VueJS (version 2.5.9) to display and modify data tables within an administrative application. Initially, I used a basic Grid component for the data table, following an example provided here. However, I came across an e ...

Suggestions on employing Nashorn and Reactjs for serverside rendering in a production environment

Exploring the potential of Nashorn (Java's JavaScript engine 1.8+), we've encountered a few concerns: Significantly long warm-up time (Java recommends hitting the code 4000 times) Lack of strong community support for Nashorn What are your ...

When entering data into the HBase database, the """ character is being substituted with "x5C"

I am facing an issue with converting a Json string to HBase as a column using Put Bytes.toBytes conversion. The Json value I am working with is: "^~\&" However, when I check the data in the HBase database, it appears as "^~\x5C\x5C& ...

Is it possible to adjust the dimensions of the number input spinner?

When working with a number input that includes a spinner, I have encountered challenges in changing the size of the spinner itself. Specifically, I am referring to the <input type='number'> element. Despite my efforts to adjust its size thr ...