Verify whether an item exists within a nested array in ReactJS

Here is the dataset that I have:

Data:

data: { id:1
          groups:[
                  {id:1 , name: john, permissions : [{id:1 , codename="can_edit"},{id:2,codename="can_write"},{id:3,codename="can_delete"}]} ,
        
                  ]
            }

I am trying to implement conditional rendering based on the user's permissions.

             { this.validatePermission()?
            <Button type="primary" shape="circle" icon={<EditOutlined />}/>
              :
              null
              }

This will trigger the this.validatePermission() method where I will check if the required permission is present:

   validatePermission(){
    const result = this.props.data.groups.forEach(function(group) {
      // Implement logic here to return true if 'codename' matches 
     });

    return result
  }

Your assistance on this matter would be greatly appreciated. Thank you!

Answer №1

checkPermission(codeName){
    return !!this.props.person.groups.find(group => group.permissions.find(permission => permission.codename === codeName));
}

Access Granted:

{ 
  this.checkPermission('can_edit')?
  <Button type="primary" shape="circle" icon={<EditOutlined />}/>
  : null
}

For multiple permissions:

checkPermission(codeNames){
  return codeNames.every(
    codeName => !!this.props.person.groups.find(
      group => group.permissions.find(
        permission => permission.codeName === codeName
      )
    )
  )
}

Using:

{ 
  this.checkPermission(['can_edit', 'can_write'])?
  <Button type="primary" shape="circle" icon={<EditOutlined />}/>
  : null
}

Answer №2

It all comes down to the specific permission you are searching for. If you want any permission, you can use this method:

   passtest(){
    const passing = this.props.person.groups.forEach(function(group) {
      return group.permission // will be true if permission array is > 0
     });

    return passing
  }

However, if you have a particular permission in mind, you can do this:

   passtest(){
    const passing = this.props.person.groups.forEach(function(group) {
      if (group.permissions[0].id === 1) {
         return true
      }
      return false
     });

    return passing
  }

If you want to target different permissions, simply adjust this line:

if(group.permissions[0].id === 1)
as needed.

EDIT BELOW

To make things work, try structuring your permissions like this:

permissions : {codename: 'codename'}

Answer №3

   checkPermissions(){
    const canEdit = this.props.person.groups.forEach(function(group) {
      group.permissions.forEach((permission) => {
        // checking each permission for edit access
        if (permission.codename === 'can_edit') {
            return true
        }
      })
      return false
     });

    return canEdit
  }

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

StyledTab element unable to receive To or component attributes

Is there a way to use tabs as links within a styled tab component? I've tried using the Tab component syntax with links, but it doesn't seem to work in this scenario: <Tab value="..." component={Link} to="/"> If I have ...

What could be causing Typed.js to not function properly in my situation?

Having an issue with typed.js not functioning properly. Here is the code snippet: <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery-1.11.3.min.js"></script> <!-- Include all compiled plugins ...

What is the best way to keep track of a checkbox's value after unchecking it and then returning to the same slide?

Issue: By default, the checkbox is always set to true in the backend code. Even if I uncheck it using JavaScript, the value remains as true when switching between slides. Desired Outcome: If I uncheck the checkbox, the updated value should be saved so tha ...

Is there a way for the React select component to adjust its width automatically based on the label size?

After defining a React select component, it looks like this: <FormControl> <InputLabel id="demo-simple-select-label">Age</InputLabel> <Select labelId="demo-simple-select-label" id=&quo ...

What is the best method to securely install a private Git repository using Yarn, utilizing access tokens without the need to hardcode them

My initial thought was to utilize .npmrc for v1 or .yarnrc.yml for v2/3/4, but in all scenarios, Yarn does not even attempt to authenticate with Github. nodeLinker: node-modules npmScopes: packagescope: npmAlwaysAuth: true npmAuthToken: my_perso ...

Leveraging the power of AJAX with either jquery or plain javascript to parse nested JSON data and display the

Similar Question: jquery reading nested json I am seeking a reliable method to iterate through multiple sets of data stored in JSON, some of which may have deep levels of nesting. My goal is to display this data in a table format. I am uncertain abou ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

I dialed the network once, only to find it entangled in a tangle during the test

Below is the snippet of my testing code: context('event page', () => { before(() => { cy.visit('/event'); }); it('create banner', () => { cy.intercept('GET', '/events') ...

Singleton constructor running repeatedly in NextJS 13 middleware

I'm encountering an issue with a simple singleton called Paths: export default class Paths { private static _instance: Paths; private constructor() { console.log('paths constructor'); } public static get Instance() { consol ...

Elevate the element from the choice API to the organization API using this.$parent

I recently developed a Vue 3 component called "Tab" using the option API. Here is the code: export default { name: "Tab", props: { name: {required: true}, iconClass: {required: true}, selected: {default: false} }, da ...

What does the typeof keyword return when used with a variable in Typescript?

In TypeScript, a class can be defined as shown below: class Sup { static member: any; static log() { console.log('sup'); } } If you write the following code: let x = Sup; Why does the type of x show up as typeof Sup (hig ...

What is the best way to showcase a half star rating in my custom angular star rating example?

component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { projectRating ...

How to send route parameters to a controller function in ExpressJS

I'm currently working on setting up user authentication for my application using passport JS. I am facing a challenge in passing the passport variable between app.js, routes.js, and controller.js. Despite trying various approaches, I have been unsucce ...

Is it possible to adjust the width of a parent element based on the number of child

In this particular example, I have structured a header with a logo-container positioned on the left side, a menu in the center, and a button on the right. The menu consists of 5 top-level items and 2 sub-menus. <div class="container"> <div cla ...

Creating a variety of Flexslider slideshows on the fly

Check out this snippet of code: <?php foreach ($objVideos as $objVideo) : ?> jQuery('#carousel-<?php echo $objVideo->id; ?>').flexslider({ animation: "slide", controlNav: false, animationLoop: false, ...

Starting up the express server with a React client

Up until this point, my projects have relied on the create-react-app tool, with the express-server and react client kept in separate directories. However, I am now exploring alternatives to create-react-app to gain a deeper understanding of how things wor ...

Visual Editor for React Material UI - A Unique Designing Experience

I've launched a new open-source project focused on creating a visual editor specifically for React Material UI. If you're interested, feel free to check out the project link. The idea behind this project is to allow users to easily drag and drop ...

What is the best way to transfer a request parameter from a URL to a function that generates an object with matching name in JavaScript?

I need to figure out how to pass a request parameter from an express router request to a function that should return an object with the same name. The issue I'm facing is that the function is returning the parameter name instead of the object. Upon c ...

ui-grid row size set to automatically adjust using rowHeight : 'auto'

Has anyone else experienced this strange behavior with ui-grid? When I set the rowHeight to auto, each cell in the same row ends up with different heights. One of the cells contains multiline data, which seems to be causing issues for ui-grid. I've ev ...

Error: Supabase and Next.js encountered a self-signed certificate within the certificate chain causing an AuthRetryableFetchError

Encountering an error related to certificates while attempting to retrieve the user from Supabase within getServerSideProps using Next.js: AuthRetryableFetchError: request to https://[redacted].supabase.co/auth/v1/user failed, reason: self signed certifica ...