Guide to building a dual recursion menu in AngularJS using both functional and template methods

I'm currently working on developing a menu in AngularJS using template and functional recursion. The code I have written involves quite a bit of recursion, so I could really use some assistance.

Below is the menu data represented in JSON format:

var menu = {
            'users': {title: 'Users', href: '/admin/users', icon: 'fa-user', 'priority': '2'},
            'dashboard': {title: 'Dashboard', href: '/admin', icon: 'fa-home', badge: null, 'priority': '1'},
            'expert': {title: 'Expert users', href: '', icon: 'fa-cog', 'priority': '3'},
            'logins': {title: 'Social logins', href: '/admin/social-logins', icon: 'fa-lock', 'priority': '2', parent: 'expert'},
            'config': {title: 'Site config', href: '/admin/config', icon: 'fa-cog', 'priority': '1', parent: 'expert'},
            'security': {title: 'Site config', href: '/admin/config', icon: 'fa-key', 'priority': '1', parent: 'config'},
            'deploy': {title: 'Deploy', href: '/admin/deploy', icon: 'fa-upload', badge: null, 'priority': '1'},
            };

One key aspect to note is that certain items within the menu data exhibit a property referred to as parent, which indicates the respective parent key they should be nested under.

Issue #1: The objective here is to process this JSON content and arrange it in order according to priority. In cases where an item possesses a parent key, a children key needs to be created in the parent item for template recursion purposes. While I believe recursion can simplify the task at hand, I am struggling to adeptly handle the implementation.

Upon successful completion of the code refinement, the intended result would correspond with the following output:

var final = [
            {title: 'Dashboard', href: '/admin', icon: 'fa-home', badge: null, 'priority': '1', id: 'dashboard'},
            {title: 'Users', href: '/admin/users', icon: 'fa-user', 'priority': '2', id: 'users'},
            {
                title: 'Expert users', href: '', icon: 'fa-cog', 'priority': '3', id: 'expert',
                children: [
                    { title: 'Site config', href: '/admin/config', icon: 'fa-cog', 'priority': '1', id: 'config',
                        children: [{title: 'Security settings', href: '/admin/security', icon: 'fa-key', 'priority': '1', id: 'security'}]
                    },
                    {title: 'Social logins', href: '/admin/social-logins', icon: 'fa-lock', 'priority': '2', id: 'logins'}
                ]
            },
            {title: 'Deploy', href: '/admin/deploy', icon: 'fa-upload', badge: null, id: 'deploy'}
            ]

Issue #2: This matter has been resolved. Now, the focus shifts towards rendering the finalized structure utilizing AngularJS template recursion. Based on the examples available, I believe I have successfully managed to resolve this particular issue. You can view my attempt at rendering by accessing this link. The menu seems to render accurately when the data conforms to the expected format.

All that remains is tackling Issue #1, wherein the objective is to generate the final variable from the existing menu variable (potentially employing recursion).

Answer №1

Give this a shot: (By the way, the JSON example's output isn't exactly the same as the var final code you provided because 'Deploy' takes precedence over 'User' and sits at the same level (without a parent). Additionally, 'Expert User' doesn't have a 'User' parent.) You don't need recursion for this; iterative code will suffice and it's faster.

var menu = {
            'users': {title: 'Users', href: '/admin/users', icon: 'fa-user', 'priority': '2'},
            'dashboard': {title: 'Dashboard', href: '/admin', icon: 'fa-home', badge: null, 'priority': '1'},
            'expert': {title: 'Expert users', href: '', icon: 'fa-cog', 'priority': '3'},
            'logins': {title: 'Social logins', href: '/admin/social-logins', icon: 'fa-lock', 'priority': '2', parent: 'expert'},
            'config': {title: 'Site config', href: '/admin/config', icon: 'fa-cog', 'priority': '1', parent: 'expert'},
            'security': {title: 'Site config', href: '/admin/config', icon: 'fa-key', 'priority': '1', parent: 'config'},
            'deploy': {title: 'Deploy', href: '/admin/deploy', icon: 'fa-upload', badge: null, 'priority': '1'},
            };
  
function insertAccordingToPriority(element, array){
     var index = 0;
     while(array.length > index && array[index].priority <= element.priority){
          index += 1;
     }
     array.splice(index, 0, element);
}

function createFinal(original){
  var final = [];
  for(var i in original){
     original[i].id = i;
     if(original[i].parent && original[original[i].parent]){
        if(!original[original[i].parent].children) original[original[i].parent].children = [];
     insertAccordingToPriority(original[i], original[original[i].parent].children);
     }else insertAccordingToPriority(original[i], final);
  }
  return final;
}

var result = createFinal(menu);
console.log(result);

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

Prevent unnecessary re-renders of components by optimizing state changes with hooks

In my Layout component, there is a Table component with an Entry component for each row. Each row can be selected, and when a row is selected, it is added to the state so that all selected entries can be sent to a REST service later using a button. The i ...

Fatal error: The street number index is not defined

I am facing an issue with displaying decoded JSON data in my view. When I try to access the streetNumber index, I receive the following error: ErrorException (E_ERROR) Undefined index: streetNumber Below is a snippet of the data: array(11) { [0] ...

Trouble with REGEX functionality in AngularJS?

I have a code snippet where I am attempting to validate an email and phone number. However, for some reason it is not functioning as expected. I am wondering if there is a specific file that needs to be included in my code. <html ng-app="myApp"> < ...

Create the final APK file using Phonegap build directly from your local machine, without the need to

While I've been using Phonegap CLI to develop my android apps and everything has been working well, I encountered an issue when trying to create the final .apk file. I have all the necessary tools - SDK, JDK, Java, and environment variables configure ...

retrieving JSON data from the request body

I have been struggling to send a JSON String from an AJAX call to a Jersey web service. Despite researching various related questions and articles, I have not been successful in getting it to work. When monitoring my calls through Fiddler, I can see the ...

Ways to retrieve an isolated scope in a directive without utilizing a template

It is clear that when I assign a controller to an element, the element along with its children can access the controller's scope. However, it is surprising that when I include a directive with an isolated scope on an element (as an attribute), I woul ...

JavaScript/jQuery: Retrieve the correct header for every element

Looking at the given HTML structure (which is just an example and may not be entirely logical): <div id="wrapper"> <h3>First Heading</h3> <div class="row"><div class="col-12"><p class=& ...

experiencing empty JSONObject values

My goal is to create a JSONObject, but I am encountering an issue in Android Studio where it is returning null. Can you help me identify where I have gone wrong? I have attempted two different methods to create the JSONObject. Method 1: String JSONStrin ...

The error message "angularjs is unable to assign a value to the property 'students' as it is

After setting ClassesServices to the classes array, I tried adding students of the class to a new property called classes.students. However, I encountered an error message saying 'Cannot set property 'students' of undefined.' $scope.cl ...

The 'file' property of undefined throws an error in ng-file-upload

I am currently exploring the functionality of ng-file-upload from this repository: https://github.com/danialfarid/ng-file-upload I have successfully implemented the basic setup as follows: HTML: <section ng-controller="MyController"> ...

What sets apart ".. let i = index" from "..let i as index"?

Having recently delved into the world of Angular, I've been scouring YouTube for tutorials. While watching, I noticed some developers using ""let item of items; let i as index"" while others used ""let item of items; let i = index" ...

Selenium WebDriver producing unexpected results with getTitle() method

Currently, I am executing an automated test script in a selenium-webdriver environment using Phantomjs. My approach involves running the script through node.js, rather than utilizing Python or C#. The steps I took to set up the environment are outlined b ...

JavaScript - Image style alterations are not operating as expected

Let me break it down for you: onmouseover="imageOn(bg-index);" onmouseout="imageOff(bg-index);" I've got these two attributes set on a table tagged with ID table-title. These functions are included in an external JS file: If the name is 'bg-i ...

Switch modules based on user options

My goal is to process an array of image files. I have the option to select them randomly or one by one (queue) based on the configuration specified in the config.json. To start off, I create the processor and determine the appropriate image selection modu ...

Encountering an "undefined is not a function" error across all libraries

While working on ASP.Net MVC4, I have encountered an issue where I consistently receive the error message "undefined is not a function" when using jQuery functions with different libraries. Despite ensuring that every ID is correct and everything has bee ...

Encountering an error while trying to install npm formidable

Having some trouble installing the formidable JS library. It appears that https://registry.npmjs.org/formidable is currently down. I used isup.me and it seems like the registry site is completely down. Can anyone confirm if this is the issue or if there ma ...

I am new to javascript and jquery. I have encountered numerous cases involving audio players

Recently delved into learning javascript and jquery. I managed to create a basic audio player that plays short audio clips. However, I've encountered an issue where clicking the play button on one clip displays stop buttons on all clips instead of on ...

Error encountered while trying to display content in the rendering area

const Pages = () => { return ( <> <Box display="flex"> {window.location.pathname === "/profile" ? undefined : <Sidebar />} <Box flex={3}> <Navbar /> <Routes> {/* Cont ...

Utilize the hash key for creating a CSV-compatible format

I am attempting to create a CSV-ready output using jq and would like to utilize the nested hash key along the way. In this scenario, http and https should be reused to generate a format ready for CSV ([]...). Original { "google.com":{ ...

Issue detected with Bundler: Configuration object is not valid. The initialization of Webpack used a configuration object that does not align with the API schema

I am currently struggling to make my bundler compile properly. When trying to get it working, I encountered this error message in my terminal along with my webpack.config.js file. Here is the issue reported by the terminal: Invalid configuration object. ...