Is there a way to retrieve the sub-child menu data from a JSON file?

I am currently working on creating a horizontal menu from a json file. However, I am facing issues in retrieving the subchild elements properly. Below is an example of my json file:

var data = [{
    "menu":[
        {
            "MenuId":1,
            "MenuName":"Home",
            ...
         }
     ]
}
];
$(function() {
for(var i = 0, j = data[0].menu.length; i<j; i++) {
    var root_menu = data[0].menu[i];
    if(root_menu.hasOwnProperty("MenuId")) {
      ...
}
});

I need assistance in accessing the sub child elements using this json file structure. You can view my code in action at http://jsfiddle.net/JcU4G/9/. The issue lies with the submenu under Home instead of being under Administration as intended, and it should further contain another set of submenus.

Answer №1

To retrieve the data, consider using data[0].menu. However, note that the data variable is not in JSON format; it is actually an array. You should remove the square brackets at the beginning and end of the variable.

Instead of:

var data = [{
  menu: [
    {
       'Menu1'

You should have:

var data = {
  menu: [
    {
       'Menu1'

Now, data is an object. This way, your for loop will iterate over the keys in the object rather than a count.

for(var key in data.menu) {
    var root_menu = data.menu[key];

I have made these changes to your Fiddle; hopefully, this aligns with what you were looking for.

Edit: http://jsfiddle.net/buUtB/1/

Answer №2

If you're looking to create a menu using recursion, this code snippet might be helpful.

Instead of creating the menu itself, the provided code simply outputs each menu name to the console. However, it serves as a demonstration on how to iterate through an object effectively. You would need to modify the logging part to actually render your menu on a webpage.

for (var i in data[0].menu) {
    displayMenu(data[0].menu[i]);
}

function displayMenu(menuNode) {
    console.log(menuNode.MenuName);
    for (var i in menuNode.Menus) {
        displayMenu(menuNode.Menus[i]);
    }
}

This recursive function is called for each sub-menu within the main menu structure.

To properly render the menu items, consider passing a 'parent' parameter to keep track of which menu item each sub-menu belongs to. If the 'parent' parameter is null, it signifies that a new root menu element should be created on the page rather than a sub-menu element.

For example:

for (var i in data[0].menu) {
    displayMenu(data[0].menu[i], null);
}

function displayMenu(menuNode, parent) {
    if (parent == null) {
        // Render root menu element in HTML
    } else {
        // Render sub menu element in HTML related to parent
    }
    for (var i in menuNode.Menus) {
        displayMenu(menuNode.Menus[i], menuNode);
    }
}

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

Error in decoding JSON while creating an index in Azure Search

I'm currently utilizing the django framework and attempting to set up an index in the Azure portal through their REST API guide. However, upon sending my post request, I encountered the following error: JSONDecodeError at /createIndex Here is the m ...

My website includes a <div> section that features both an image and a <figcaption>. However, when I attempt to apply padding to the <figcaption>, it does not seem to take effect

I've been trying to troubleshoot this code, but the padding just won't cooperate and I can't seem to figure out why. .img-caption { visibility:hidden; width:22%; height:435px; background-color:#f9f4e3; ...

"Update your Chart.js to version 3.7.1 to eliminate the vertical scale displaying values on the left

Is there a way to disable the scale with additional marks from 0 to 45000 as shown in the screenshot? I've attempted various solutions, including updating chartjs to the latest version, but I'm specifically interested in addressing this issue in ...

What is the best way to connect the imagemap shape with the checkbox?

I need assistance with synchronizing an imagemap collection of shapes and checkboxes. How can I ensure that clicking on a shape selects the corresponding checkbox, and vice versa? Imagemap: <div class="map_container"> <%= image_tag("maps/main ...

The PHP script's header() function is failing to execute

Recently, I encountered an issue with my JavaScript code that calls a backend PHP script using AJAX. The main function of the AJAX request is to send user login data (username and password) to the PHP script, which in turn queries this information on the S ...

I am facing an issue with jQuery wherein I am unable to dynamically assign a variable to an element's

I have a function that adds list elements to the #exercise-checkbox-list using AJAX. This function works fine on the backend side, but there is an issue where the second time a user adds an exercise, the new exercise's ID ends up being the same as the ...

What is the best way to implement a custom layout with nuxt-property-decorator?

Summary of Different Header Components in Nuxt In order to set a different header component for a specific page in Nuxt, you can create separate layout files. layout ├ default.vue // <- common header └ custom.vue // <- special header for s ...

Accessing content from a different HTML document

I'm currently working on a project using node.js where I need to take input from a text box in an HTML file and store it in an array. However, I'm struggling with how to achieve this. My ultimate aim is to create a chat application, and I believe ...

What to do when faced with an NPM issue: Resolving the error "Unable to assign properties to null (setting 'parent')"

The issue arises in NPM when working within a monorepo that utilizes the NPM workspaces feature. Within my monorepo, I have five packages: a, b, c, d, and e. Additionally, I have a package located in a separate repository that is not part of the workspace, ...

Changing the background color of a table cell using PHP based on data retrieved from a database table

Currently, I am developing an attendance system where users can mark their attendance. Additionally, the page contains a calendar displaying the current month. My objective is to modify the color of table cells based on the attendance status: 1. Green fo ...

Guide to showcasing a JSON object beginning at a designated position?

Having a json object as an example var obj = [{name: "ana", gender: "woman"}, {name: "ben", gender: "man"}, {name: "andrew", gender: "man"}, {name: "jake", gender: "man"}] Looking to display the list from the 2nd index to the last index of th ...

another option to JQuery .slideDown()

Are there any alternatives to using jquery slideDown() that are known? I'm asking this because it seems like slideDown should be called roll down instead, since it seems to unravel the contents rather than sliding them down. Here is an example of th ...

What is the best way to utilize variables in order to style this image inside a selector?

Struggling with adding dynamic styling to an image inserted into a div through a selector. Despite successful testing of the style changes, I am stuck on how to assign variable values for the properties. Various syntax attempts have failed so far. functi ...

Exploring the world of Json/Hstore elements within postgresql

Here is the information stored in my table: STUDENT_INFO TABLE Column Data type ------------------ ID number STUDENT_DATA hstore Displayed below is the actual data: ID STUDENT_DATA 1 "config"=>"{"env": "TEST", "student": "10508"}", "payload"= ...

How can you emphasize the most recent entry in a Datatable?

When dynamically adding rows to my datatable using ajax, I need to apply a specific CSS style to the last row. However, the challenge is that this last row may be on a different page due to datatable pagination. Here's what I attempted: table.row().i ...

Alter the properties based on the size of the window

I am working with React-Spring and I need to adjust the offset of a component when the window size changes. I attempted the following solution, but it is not functioning correctly and requires me to refresh the browser each time. <ParallaxLayer ...

Extraction of Data from JSON Objects

Previously, I received a lot of help from this community, but now it seems like the topic has gone cold. As a result, I had to create a new account for further assistance. Following all the suggested fixes, I am currently facing an issue with obtaining pre ...

Creating a Typescript type for the react-intl component within a single file

Currently, I'm trying to incorporate the injectIntl component directly in the file instead of using the traditional export default injectIntl(Component). However, I am encountering difficulties when it comes to typing the component. This is a snippet ...

A guide to converting variables into a JSON Object in Javascript

I am looking for a way to insert external variables into a JSON object. An example of what I want: var username = "zvincze"; And then, using that variable to inject it into a JSON object: var json = '{"username":"VARIABLE_GOES_HERE"}' var obj ...

Is there a way to incorporate CSS or tables when converting HTML to PDF using JavaScript?

While working on a project, I successfully converted an HTML file into a PDF. However, the output did not display the CSS design. Can anyone provide suggestions on how to include CSS design in the PDF file? Below is the JavaScript function code: $(funct ...