Filtering an array using criteria: A step-by-step guide

Currently, I am developing a system for Role Based permissions that involves working with arrays. Here is an example of the array structure I have:

let Roles = {
  [
    { model: 'user', property: 'find', permission: 'allow' },
    { model: 'user', property: 'create', permission: 'allow' },
    { model: 'user', property: 'update', permission: 'deny' },
    { model: 'user', property: 'delete', permission: 'deny' }
  ],
  [
    { model: 'registration', property: 'find', permission: 'allow' },
    { model: 'registration', property: 'create', permission: 'deny' },
    { model: 'registration', property: 'update', permission: 'deny' },
    { model: 'registration', property: 'delete', permission: 'deny' }
  ]
  [
    { model: 'schedule', property: 'find', permission: 'allow' },
    { model: 'schedule', property: 'create', permission: 'allow' },
    { model: 'schedule', property: 'update', permission :'allow'},
    { model: 'schedule', property: 'delete', permission: 'deny' }
  ]
}

The desired output I am trying to achieve is as follows:

  let userPermissions = [{
  'menu_name': 'user',
  'canFetchData': true,
  'canCreateData': true,
  'canUpdateData': false,
  'canDeleteData': false,
}]

let registrationPermissions = [{
  'menu_name': 'registration',
  'canFetchData': true,
  'canCreateData': false,
  'canUpdateData': false,
  'canDeleteData': false,
}]

let schedulePermissions = [{
  'menu_name': 'schedule',
  'canFetchData': true,
  'canCreateData': true,
  'canUpdateData': true,
  'canDeleteData': false,
}]

To generate these results, the conditions are simple: if the permission is 'allow', then set it to true; otherwise, set it to false.

In my attempt to achieve this, I encountered issues where values were getting overridden in the second array. To address this, I implemented conditional statements within a function that filters and applies permissions based on the data provided:

  private canFetchData;
  private canCreateData;
  private canUpdateData;
  private canDeleteData;

filterAndApplyPermission(data) {
for (let i = 0; i < data.length; i++) {
  if (data[i].property === 'find' && data[i].permission === 'ALLOW') {
    this.canFetchData = true;
  } else if (data[i].property === 'create' && data[i].permission === 'ALLOW') {
    this.canCreateData = true;
  } else if (data[i].property === 'update' && data[i].permission === 'ALLOW') {
    this.canUpdateData = true;
  } else if (data[i].property === 'delete' && data[i].permission === 'ALLOW') {
    this.canDeleteData = true;
  }
}

const grouped_permission = {
  'menu': data[0].model,
  'canFetchData': this.canFetchData,
  'canCreateData': this.canCreateData,
  'canUpdateData': this.canUpdateData,
  'canDeleteData': this.canDeleteData,
};
   return grouped_permission;
 }

Answer ā„–1

Discover the array of permissions associated with a specific user using the filter method:

roleInfo
.filter(roles=>roles[0].model==="schedule")[0]

Utilize reduce to construct your object and implement switch for each property.

rolesForUser
.reduce(
  (info,item)=>{
    switch(item.property) {
      case 'find':
        info.canFetchData = (item.permission==='allow')?true:false
        break;
      //other cases
    }
    return info;
  },
  {menu_name : user}//initial info object with menu_name set to user
);

const roleInfo = [
  [
    { model: 'user', property: 'find', permission: 'allow' },
    { model: 'user', property: 'create', permission: 'allow' },
    { model: 'user', property: 'update', permission: 'deny' },
    { model: 'user', property: 'delete', permission: 'deny' }
  ],
  [
    { model: 'registration', property: 'find', permission: 'allow' },
    { model: 'registration', property: 'create', permission: 'deny' },
    { model: 'registration', property: 'update', permission: 'deny' },
    { model: 'registration', property: 'delete', permission: 'deny' }
  ],
  [
    { model: 'schedule', property: 'find', permission: 'allow' },
    { model: 'schedule', property: 'create', permission: 'allow' },
    { model: 'schedule', property: 'update', permission: 'allow' },
    { model: 'schedule', property: 'delete', permission: 'deny' }
  ]
];

const getRoleForUser = (user,roleInfo) =>
  roleInfo
  .filter(roles=>roles[0].model===user)[0]
  .reduce(
    (info,item)=>{
      switch (item.property) {
        case 'find':
          info.canFetchData = (item.permission==='allow')?true:false
          break;
        case 'create':
          info.canCreateData = (item.permission==='allow')?true:false
          break;
        case 'update':
          info.canUpdateData = (item.permission==='allow')?true:false
          break;
        case 'delete':
          info.canDeleteData = (item.permission==='allow')?true:false
          break;
        default:
          throw new Error(`${item.property} is an unknown permission`);
      }
      return info;
    },
    {menu_name : user}
  );

console.log(getRoleForUser("registration",roleInfo));

Answer ā„–2

As you brought up in your query

Concerning Role Based permissions, here is the array I have

You can structure your permission object as shown below:

const permissionObj = {
    find: 'canFetchData',
    create: 'canCreateData',
    update: 'canUpdateData',
    delete: 'canDeleteData'
}

To iterate through the array, utilize the reduce() function and integrate the permissionObj within it.

DEMONSTRATION

const dataObj =[[{
            model: 'user',
            property: 'find',
            permission: 'allow'
        }, {
            model: 'user',
            property: 'create',
            permission: 'allow'
        }, {
            model: 'user',
            property: 'update',
            permission: 'deny'
        }, {
            model: 'user',
            property: 'delete',
            permission: 'deny'
        }],...
.as-console-wrapper {  max-height: 100% !important;  top: 0;}

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

Issue: Unable to utilize import statement outside a module as per the guidelines of the vue-test-utils official tutorial

I'm struggling to get Vue testing set up with vue-test-utils and jest. I followed the installation guide at https://vue-test-utils.vuejs.org/installation/#semantic-versioning, but can't seem to figure out what's wrong. Here's what I&apo ...

Verify that all elements sharing a common class are concealed

I'm facing a simple issue where I have a list with identical class names. When one of them is clicked, it animates out of the container and then redirects you. The list also includes a hide button. My goal is to receive a browser alert when all items ...

Leveraging JavaScript to access the margin-top property of the HTML and body tags

I'm having trouble retrieving the "marginTop" style property from the <html> and <body> tags. While Chrome developer tools shows that margin-top is being set via in-HTML CSS: <style type="text/css" media="screen"> html { margin-top: ...

I need to change a website into a string so that I can analyze it with javascript. How can I do this?

Currently, I am in the process of creating a website for my video game servers. The admin tool we use outputs the current server status in a .json format as a large text string to this specific URL: My goal is to retrieve the entire text string from the p ...

PHP array index malfunction

I've been banging my head against the wall for hours trying to figure out what I'm doing wrong here. It just doesn't add up. <?php date_default_timezone_set('America/New_York'); $json = file_get_contents('https://www ...

unable to adjust the maximum height limit

I've been struggling to set a maximum height on the slider I'm currently using. No matter what height value I input, it doesn't seem to take effect. Additionally, I attempted setting the width for the echo img row in the PHP section but enco ...

What is the method for implementing a Redirect in React Router?

I'm new to React and facing a challenge. My goal is to implement a conditional Redirect, and I have created a function called errorCapture for this purpose. The function should trigger a Redirect based on a specific condition. I have included the ret ...

I am finding that the text I am creating using context.fillText keeps getting distorted within the canvas

I am attempting to place text inside a canvas element. The HTML markup for the canvas is as follows: <canvas id="leaderboard2" style="position: fixed; right: 1250px; top: 140px; width: 230px; height: 330px;"></canvas>. Des ...

I am encountering an issue where the POST data is not being successfully sent using XMLHttpRequest unless I include

I have a unique website where users can input a cost code, which is then submitted and POSTed to a page called 'process-cost-code.php'. This page performs basic validation checks and saves the information to a database if everything is correct. T ...

Why is it that useEffect is functioning correctly only on the first occasion?

Recently, I've been facing significant challenges with React's useEffect and States. The issue arises when I redirect to the main page of my app and then attempt to use them again. In the following component, everything seems to function correct ...

Is there a way to adjust the width of the datepicker on my device?

I've been attempting to adjust the width of the date picker, but I'm having trouble achieving it. Below is my code: import React from "react"; import ReactDOM from "react-dom"; import { DatePicker, RangeDatePicker } from &qu ...

Customizing the initial page layout in Elm

I am new to Elm and I need help with a particular issue. Can someone provide guidance or direct me to a useful resource for solving this problem? The challenge Iā€™m facing involves editing the start page of a website by removing specific elements, as list ...

Is it possible to develop an image that can be zoomed in and out using the mouse

$(document.createElement('img')) .width(imgW) .height(imgH) .addClass('img_full') .attr('src', $(this).attr('data-src')) .draggable() .css({ &a ...

What is the best way to display a nested JSON object structure?

{ "Title": "Jurassic Park", "Year": "1993", "Rated": "PG-13", "Released": "11 Jun 1993", "Runtime": "127 min", "Genre": "Action, Adventure, Sci-Fi", "Director": "Steven Spielberg", "Writer": "Michael Crichton, David Koepp", "Actors": "Sam ...

"Encountered an issue: Error occurred while attempting to synchronize Protractor with the page" during the execution of Protractor tests

I am facing an issue while running Protractor tests on a web application that includes both Angular and non-angular elements. Here is the structure of my code: describe("Test Name", function() { it("Test case", function() { // starting with steps on ...

Encountering the error message "Module 'request' not found" despite the fact that I've already included the request module

I'm currently facing an issue with my Cloud Function that involves using the request library. After installing the request package using npm install request, I noticed it's located in the node_modules directory, just like all the other packages: ...

What causes an error during the compilation of an Angular package containing a singleton class?

I am currently in the process of creating an Angular library. Within this library, I have developed a singleton class to manage the same SignalR connection. Here is the code implementation: import * as signalR from '@microsoft/signalr'; export c ...

What is the best way to implement rate limiting for Next.js server actions?

In my current project, I have implemented server actions in next.js following the guidelines provided on Server Actions Although everything is functioning properly, I am now looking to add rate limiting to the server action to prevent potential spam or at ...

Challenges when working with AJAX/jQuery in terms of fetching JSON data and setting dataType

I am currently facing a challenge with my practice of AJAX/jQuery coding. Despite my efforts to learn and improve, I find the concepts of jQuery and AJAX quite perplexing. Specifically, I am struggling to understand dataTypes and how to manage different ty ...

Developing a dynamic user interface using an Angular framework and populating it with

I am currently learning Angular (version 1) and facing an issue with my layout. I need to dynamically change the navigation based on the type of user that is logged in. To achieve this, I make an API request when the page loads to fetch the user object dat ...