Contrasting the functionality of multidimensional arrays and implementing a property to each individual element, extending to all levels of nested

Currently, I am tackling the permission aspect of my application. The scenario involves developing a Vue application that receives data from a Laravel backend created by another individual. My current challenge lies in determining whether a permission is checked and active under a specific role. In this setup, permissions are associated with roles, meaning when creating a role, it's necessary to identify which permissions are linked to that role.

To start, I retrieve all permissions and organize them into an array structure. This array contains parent permissions along with their respective child permissions, extending up to four levels deep.

The permissions structure is as follows:

{ 
    "data": [
        {
            "id": 1,
            "name": "Suppliers management module",
            // Additional permission details...
            "children": [
                {
                    "id": 2,
                    "name": "Suppliers management module settings",
                    // Additional permission details...
                    "children": [
                        {   
                           // More detailed permission information...
                            "children": [ ]
                        },
                        {  
                           // Detailed permission info...
                            "children": [ ]
                        },
                        // And so forth for hierarchy
                    ],
                },
              // Other hierarchical permission structures...
            ]
        },
        // Repeat similar structures for other permissions
    ]
}

Upon retrieving a specific role, the associated permissions need to be cross-referenced against the entire list of permissions. This comparison helps distinguish existing permissions for the role and those that do not exist within its scope.

The approach taken for comparison involved:

// Initializing arrays for permissions
this.permissions = response.data.data;

// Collating all permissions into one array
this.permissions.forEach((element) => {
    this.AllPermissions.push(element);

    element.children.forEach((one) => {
        this.AllPermissions.push(one);

        one.children.forEach((two) => {
            this.AllPermissions.push(two);

            two.children.forEach((three) => {
                this.AllPermissions.push(three);
            });
        });
    });
});

// Storing permission IDs of a role in an array
this.role.permissions.forEach((element) => {
    this.permissionsNumbers.push(element.id);
});

// Comparing permissions for role assignment
this.AllPermissions.forEach((item) => {
    if (this.permissionsNumbers.includes(item.id)) {
        item.check = 1;
    } else {
        item.check = 0;
    }
});

While the above method works, it may appear inelegant due to multiple nested loops and the potential manual adjustments needed if the permission hierarchy changes. Additionally, handling the resulting flat array of permissions tied to a role raises concerns about readability and maintenance.

Exploring more streamlined approaches that retain the hierarchical nature of permissions during comparisons would greatly enhance the efficiency and scalability of this process. Any insights or suggestions on optimizing this workflow while maintaining clarity are highly appreciated. Feel free to seek clarification if any part requires further elaboration.

Answer №1

Illustrating the concept of recursively calling an array and emphasizing that objects are passed by reference in JavaScript, allowing for direct edits during iteration using the original array. It may require some customization to fit your specific class structure.

class SecurePermissions{
    constructor(permissions, role){
        this.validPermissions = [];
        this.role = role;
        this.role.permissions.forEach((element) => {
            this.validPermissions.push(element.id);
        });
        this.AllowedPermissions = this.verifyPermissions(permissions);
    }

    verifyPermissions(perms, parentValid){
        perms.forEach((perm) => {
            if(isValidPerm){

                //Parent permission was valid, so all children are also considered valid
                perm.validation = 1;

            }else if(this.validPermissions.includes(perm.id)){

                //Check against the permissions assigned to the role
                perm.validation = 1;
            }else{

                //Permission is invalid if not present in the role's permissions or its ancestors'
                perm.validation = 0;
            }

            //Recursively check child permissions
            if(typeof perm.children != 'undefined') this.verifyPermissions(perm.children, perm.validation);
        });

        return perms; //Return modified array
    }

}

If you prefer AllPermissions to only contain valid permissions:

class SecurePermissions{
    constructor(permissions, role){
        this.AllPermissions = [];
        this.validPermissions = [];
        this.role = role;
        this.role.permissions.forEach((element) => {
            this.validPermissions.push(element.id);
        });
        this.verifyPermissions(permissions);
    }

    verifyPermissions(perms){
        perms.forEach((perm) => {
            if(this.validPermissions.includes(perm.id)){
                this.AllPermissions.push(perm);
            }else{
                //If the role lacks this permission, it is deemed invalid
                if(typeof perm.children != 'undefined') this.verifyPermissions(perm.children, perm.validation);
            }
        });
    }

}

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

Phonegap: Displaying audio controls and metadata for my audio stream on the lock screen and in the drop-down status bar

After successfully creating my initial android app for phonegap 5.1 that plays an audio stream, I am currently facing an issue. I am unable to locate any solutions: How can I display audio controls and metadata of my audio stream on the lock screen as well ...

Is there a way to seamlessly transition between images in a slider every 3 seconds using javascript?

<!DOCTYPE html> <html> <head> <title>Hello</title> <meta http-equiv="Content-Type" type="text/html" charset="UTF-8"/> <style> *{margin:0; padding:0;} .mySlides{ position:relative; width:1000px; ...

Is there a way to update the button's value upon clicking it?

I've hit a roadblock in my tic tac toe game project during class, and I've been struggling for the past two days to get the X's and O's to show up. The deadline for this assignment is tomorrow! Here are the task requirements: COMPSCI20 ...

I'm sorry, there seems to be an issue with connecting to the database at the moment. The error code SequelizeConnectionRefusedError is indicating that the connection is being refused at 127.0

I'm currently facing an issue with my code. I've set up a local MySQL database using XAMPP, but for some reason, sequelize is unable to connect to it. import { Sequelize } from "sequelize"; const user_auth_db = new Sequelize('db_n ...

Sending 3D array indexes as arguments to a function

Here is the complete code I have so far, if you need to refer to it. I am working with a 3D array that stores high and low temperatures for specific days and months. I am required to pass this array through the following function: double average_array(in ...

How to pass the ng-repeat $index value as a parameter in AngularJS

Within the code snippet provided, there is a shell page index.html and a partial view currently utilized by two different controllers. The static data in AppController is connected to the list.html partial view and displayed as a table. In the JavaScript p ...

The integration of Angular 6 with AngularJS components fails to load properly in a hybrid application

Currently, I am in the process of upgrading a large AngularJS version 1.7.3 to a hybrid app using Angular 6. The initial phase involved converting all controllers/directives into an AngularJS component. Subsequently, I created a new Angular 6 project skele ...

The TypeError encountered when using vue.js push arises from attempting to access the 'name' property of an undefined value

Here is a code snippet I am working with: new Vue({ el: '#core', data: { checkedThemes: [] ... } }) Afterwards, I have the following code: mounted() { ... var theme = parseInt(parameters['theme&apo ...

Create a function that takes an array as input and retrieves the element in the array that corresponds to the specified question

To solve this problem, I'm tasked with creating a function called findAnswers(answers, questions). The function should return the item in the array that corresponds to the given question. If none of the student's answers match the question, the f ...

How can you use Require.context in Webpack to import all .js files from a directory except those ending in `_test.js`?

My objective was to develop a script that accomplishes the following tasks: Import all JS files from a directory excluding those ending in _test.js Set up a module.exports containing an array of module names extracted from those imported files. Initiall ...

Navigating with Vue Router in a Nuxt JS vuex Store

In my app, I'm currently developing a login/register system using Firebase and Vuex for authentication and database management. Within Nuxt JS, I have implemented actions to create a user, log them in, and sign them out. After a successful registrati ...

Unlocking Iframe Mode in CKEditor 4

I've encountered a difference between CKEditor 3 and CKEditor 4. In CKEditor 3, when I call the method CKEDITOR.replace('#textAreaId'), it wraps the editor in an iframe. However, in CKEditor 4, when I call the same method (not inline), the i ...

Mirror the input text to another input within a for loop

I have a list of questions displayed, each with an input field for entering a phone number. How can I use jQuery or JavaScript in a for-loop to mirror the text entered in the first phone input box to all subsequent phone input boxes? ..Enter your phone... ...

What is the best way to dynamically change the style options of a select dropdown based on a specific condition?

My knowledge of JavaScript is limited, but I require some JS functionalities for my Django project. Your assistance would be greatly appreciated. I want to customize the style of option tags within the select tag with the id "id_car_model". The goal is to ...

Alert message in jQuery validation for the chosen option value

I am attempting to validate a combo box with the code provided below. Currently, I receive multiple alert messages even if one condition is true. My goal is to only display one alert message when a condition is met and highlight the other values in red. Th ...

Measuring Load Time Percentage in AngularJS Using $http Requests

I am currently utilizing Angular with my Rails application. I have a sample app and I am interested in displaying the response time required to load a response in Angular. For example, When loading a response of an array containing 100,000 elements, I w ...

transferring data through hyperlink tags

In PHP, I am currently developing a module that enables me to view and access all the users on my website. To achieve this, I am retrieving all the user names from the database and creating anchor links for them simultaneously. Now, I want to associate dat ...

I am currently developing a user-friendly bug reporting system that is fully functional. However, I have encountered a persistent error message in the console related to Discord.js that I am determined to resolve

In coding this bot, we are using the Discord.js library and some custom functions to handle bug reports from users. The bugreport command allows users to submit their reports, which are then sent to a specific channel for further action. However, we encou ...

Using Vue.js to create a list of select boxes with v-for loop

I need help with a Vue JS issue Here is the code snippet I am working with: <div v-for="benefit in benefits" track-by="$index" class="Quote__list"> <div class="Benefit Form--default"> <select v-model="benefitType" @change="updateBenefit ...

Issue with DIV height in Internet Explorer occurs only when application is accessed using server name

Encountering a unique issue specific to IE (confirmed in v8 and v9). When utilizing jquery to determine the height of a div: $('#sys_MainPage').height() In Chrome, Firefox, and when accessing using the IP address, this code returns around 26 ...