Create an Interactive Menu Using JSON Data

Looking for guidance with angularjs as a beginner, I'm interested in creating a dynamic menu using JSON array.

{
"Pages": [{
"PageId": 1,
"PageTitle": "Home",
"PageContent": "Home Page Content",
"MenuType": "MainMenu",
"ParentMenu": null,
"PageStatus": "Active",
"PageType": true
}, {
"PageId": 2,
"PageTitle": "About",
"PageContent": "about content",
"MenuType": "SubMenu",
"ParentMenu": Home,
"PageStatus": "Active",
"PageType": true
}, {
"PageId": 3,
"PageTitle": "Contact",
"PageContent": "Contact Us Content",
"MenuType": "MainMenu",
"ParentMenu": null,
"PageStatus": "Active",
"PageType": true
}]
}

I envision the menu structure to be:

- Home
  - About
- Contact

Your assistance and insights would be highly appreciated. Thank you!

Answer №1

If you want to transform your menu into nested HTML lists that can be easily added to your webpage, check out this function.

const menu = {
  "Categories": [
    { "CategoryId": 1, "CategoryName": "Food",       "ParentCategory": null },
    { "CategoryId": 2, "CategoryName": "Drinks",     "ParentCategory": "Food" },
    { "CategoryId": 3, "CategoryName": "Desserts",   "ParentCategory": "Food" },
    { "CategoryId": 4, "CategoryName": "Beer",       "ParentCategory": "Drinks" },
    { "CategoryId": 5, "CategoryName": "Wine",       "ParentCategory": "Drinks" },
  ]
}

// generic function for creating an element
const createElement = (type, className, text) => {
  const el = document.createElement(type)
  el.className = className
  if (text) {
    el.appendChild(document.createTextNode(text))
  }
  return el
}

// display the menu in a hierarchical format
const createMenu = (menu, parentName = null, level = 0) =>
  menu.reduce((ul, item) => {
    if (item.ParentCategory === parentName) {
      const li = createElement(`li`, `category__item`, item.CategoryName)
      ul.appendChild(li)
      // recursively call itself with the current CategoryName as the parentName
      const children = createMenu(menu, item.CategoryName, level+1)
      if (children.childNodes.length) {
        li.appendChild(children)
      }
    }
    return ul
  }, createElement(`ul`, `category__list level--${level}`))

const app = document.querySelector(`#app`)
app.appendChild(
  createMenu(menu.Categories, null)
)
console.log(app.innerHTML)
<div id="app"></div>

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

Is there a way to retrieve the values of a checkbox from a location outside the form where it is initially defined?

After successfully developing a script that deletes rows from a table when a checkbox is selected, I encountered an issue where the values of the checkboxes were not accessible outside of the form action they were placed in. The checkboxes and correspondin ...

The event listener for 'ended' is triggering multiple times

I am in the process of developing a music app, and my goal is to have the next song automatically play when the current one ends. However, I am facing an issue where the EventListener seems to be triggered multiple times in succession - first once, then tw ...

Convert the PHP API response into a float number and ensure that it returns as a whole number

When I make a call to an external API, I am able to successfully retrieve the result. However, I am encountering an issue where a numerical value in one specific field is being converted into a float number. Here is how I am handling the API response: pr ...

Parsing JSON data involves decoding characters like "{", "["

When attempting to json_decode the following data: "main":{ "temp":9.04, "temp_min":9.04, "temp_max":9.04, "pressure":938.13, "sea_level":1037.57, "grnd_level":938.13, "humidity":87 }, "weather":[ { ...

Sequelize associations are not functioning optimally as expected

Trying to display a nested relationship: Cat.hasMany(legs) Leg.belongsTo(cat) Leg.hasOne(paw) paw.hasMany(leg) This is the Cat Model: module.exports = (sequelize, DataTypes) => { const Cat = sequelize.define('Cat', { us ...

How can I prevent my code from resetting every time a state update occurs?

https://i.sstatic.net/snSGl.pngI've coded a program that creates a 10x10 grid with 5 boxes of varying sizes. When you click on a box, an x is added to its content and the turn state is set to false. The issue arises when the code re-runs after each s ...

Check if the user is null using React's useEffect hook and then perform a

I am currently working on implementing a protected route in Next JS. I have included a useEffect to redirect to the sign-in page if there is no user detected. const analytics = () => { const { userLoaded, user, signOut, session, userDetails, subscri ...

React's useState feature is doubling the increment

I have created a basic form management system with a historical feature. A simplified version of this system can be seen on codesandbox import { useState } from "react"; import "./styles.css"; const sample = ["what", "w ...

Output the contents of a nested object

After setting up a variable containing music library data... var library = { tracks: { t01: { id: "t01", name: "Code Monkey", artist: "Jonathan Coulton", album: "Thing a Week Three" }, t02: { id: " ...

What is the reason behind the addition of '.txt' by the Next.js `Link` Component when redirecting to `href='/'` on GitHub pages?

My website is hosted on github-pages, and I am using the Link Component from Next.js to navigate within it. However, when I click on a component with the href="/", it adds .txt to the end of the URL. My website follows the /app structure. I have ...

Evaluating Jasmine unit tests using promises with odata

I am new to working with Angular and unit testing in Angular. Our project involves using odata for performing CRUD actions on the database, so we have created a service for this purpose. Here is a snippet of our service code: function DatabaseService($htt ...

Incorporate create-react-app with Express

Issue - I am encountering a problem where I do not receive any response from Postman when trying to access localhost:9000. Instead of getting the expected user JSON data back, I am seeing the following output: <body> <noscript>You need to ...

I am wondering why the JSON data retrieved through $http.get and stored in the $scope object is not displaying in the binding expression

After retrieving JSON data from a JSP file in AngularJS, I stored it inside a $scope object. However, the data was not displaying when I tried to print it within the binding expression. Strangely, the data was visible in the console log when using console. ...

What steps should I take to modify my json file in order to populate a datagridview successfully?

I am facing an issue with the JSON data I receive, which seems to be incompatible with populating a datagridview. Despite trying various solutions from my research, I have not been able to resolve this problem. This is how I fetch my JSON data: using (v ...

Transforming an array of HashMaps into a JSON object within a servlet and showcasing it on a JSP page

Looking to extract all table rows and store them in an array of hashmaps, then convert them into a JSON object to be sent to a JSP page using Ajax and jQuery. Struggling with displaying the content on the JSP page. I've written the code below but need ...

manipulating and merging a json data structure in PHP

Here is a json string that I need help parsing: { "6ad416d7-551a-41e3-9103-42d0a6a14d95":{ "0":{ "value":"KOSHER ONE" } }, "acb022a1-2369-4a20-8b6e-714387b81a6c":{ "0":{ "value":"PAREVE" } }, "f4ef2148-270e-4d9d-913d-f1a4ed2a73f0":{ "0 ...

Angular: Enhancing View Attribute by Eliminating Extra Spaces

I'm using an ng repeat directive to dynamically set the height in my code. <ul> <li ng-repeat="val in values" height-dir >{{val.a}}</li> </ul> app.directive('heightDir',function(){ return { restrict: ' ...

MUI's Checkbox with Radio Button feature functionality

In my project, I am looking to implement a Checkbox with radio button behavior inside an Accordion component. The challenge here is that only one item should be selected at a time. If one item is checked, it should automatically uncheck the previously sele ...

Having trouble retrieving values from JSON properties

My mind is boggled by this issue, and I have a feeling it's just a simple oversight! I'm dealing with a service that sends back a JSON object: [{"accountId":"0000004000006195","title":null,"firstName":"JOE","middleName":"BLOG","lastName":"BLOGG ...

Ng-repeat seems to be having trouble showing the JSON data

Thank you in advance for any assistance. I have a factory in my application that utilizes a post method to retrieve data from a C# function. Despite successfully receiving the data and logging it to the console, I am facing difficulties in properly display ...