Looping Through Key-Value pairs in an Object Using Javascript

var roles = {
    Guest: ["CAN_REGISTER"],
    Player: ["CAN_LOGIN", "CAN_CHAT"],
    Admin: ["CAN_KICK", "CAN_LOGIN", "CAN_CHAT"]
};

I have an object called 'roles' containing different permissions for each role, and I am implementing a function to check if a user has specific permissions.

get_perms: function(player, perm) {
    let arrayLength = accounts.length;
    let name = player.name;

    if (arrayLength == 0 && (perm == "CAN_CHAT" || perm == "CAN_LOGIN" || perm == "CAN_KICK")){
        return false;
    }

    for (var i = 0; i < arrayLength; i++)
    {
        if (accounts[i][0] == name)
        {
            for (var key in roles)
            {
                if (roles.hasOwnProperty(key))
                {
                    if (accounts[i][2] == key){

                        if (roles[key] == perm){
                            for (var x = 0; x < roles[key].length; x++){
                                if (roles[key][x] == perm){
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }
        else{
            return false;
        }
    }
}

The value of account[i][2] represents the role of the player with the corresponding name. The main aim is to validate whether this role possesses the specific permission- denoted by the variable perm that is passed as an argument to the function, for instance, "CHAT_PERMS".

Answer №1

const userRoles = {
    Guest: ["CAN_REGISTER"],
    Player: ["CAN_LOGIN", "CAN_CHAT"],
    Admin: ["CAN_KICK", "CAN_LOGIN", "CAN_CHAT"]
};

const flattenedArray = Object.keys(userRoles).reduce((accumulated, current) => [...accumulated, ...userRoles[current]], []);
console.log(flattenedArray);
const rolesSet = new Set(flattenedArray);
console.log(rolesSet.has("CAN_CHAT"))

I came up with this ES6 solution to flatten the array and check for a specific role in the set:

  1. Using reduce with array spread syntax, I created a flat array such as
    [ "CAN_REGISTER", "CAN_LOGIN", "CAN_CHAT", "CAN_KICK", "CAN_LOGIN", "CAN_CHAT" ]
  2. This array is saved into a set
  3. I used the has() function to verify if the specific role exists in the set

Answer №2

Utilize a for-loop along with the function includes to verify the role and permission.

var roles = {
    Guest: ["CAN_REGISTER"],
    Player: ["CAN_LOGIN", "CAN_CHAT"],
    Admin: ["CAN_KICK", "CAN_LOGIN", "CAN_CHAT"]
};

var playerRoles = ['Admin', 'Guest'];
var perm = 'CAN_LOGIN';

var found = false;
for (var role of playerRoles) {
  if ((found = roles[role].includes(perm))) {
    console.log("Permission '"+perm+"' located in Role '" + role + "'");
    break;
  }
}

if (!found) {
    console.log("Permission '"+perm+"' not found");
}

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

Transferring data between Jade templates

In the process of building a compact CMS system prior to diving into Node.js websites using Express, Jade, and Bootstrap, I encountered a minor setback. To enhance modularity, I am employing includes for various components like the navigation header on th ...

What are the advantages of using HttpClient compared to fetch?

With the introduction of Angular 2+, HttpClient now facilitates HTTP requests sent down an RxJS observable. I'm curious about why one would opt for using HttpClient's API instead of the standard fetch for individual HTTP requests. I have a good ...

Troubleshooting problems with background-image in CSS using Javascript

My latest project involves coding to assign background images to various classes using jQuery. The image files are named in a numerical order, such as 0bg.jpg, 1bg.jpg, 2bg.jpg, and so on. for (i=0; i < 8; i++) { $('.hpCarousel:eq('+i+' ...

The HTML was generated without any styling properties assigned

After running my script on a galaxy tab, I encountered a strange issue. I created an HTML element (div) and attempted to access the style attribute, only to receive an error message indicating that style is null. Below is the code snippet: var newDiv = d ...

Steps to remove a row from a table in a ReactJS component

I'm struggling with implementing a delete operation for table rows and encountering errors. Any assistance in resolving this issue would be greatly appreciated. Since I am unsure how to set an auto-incrementing id, I used Date.now(). Now my goal is t ...

Issue with spotlight / shadow camera cutoff in Three.js

I've been grappling with a problem for hours now and could really use some help. So, I have this spotlight in my scene that I imported from a collada file, but for some reason, the shadow is getting cut off. Even when I turn on the camerashadow helpe ...

Is it possible for me to send transactions asynchronously using polkadot-js?

After thoroughly going through the official documentation, I stumbled upon a page discussing how to transfer using polkadot-js const transfer = api.tx.balances.transfer(BOB, 12345); const hash = await transfer.signAndSend(alice); I am curious if it' ...

Issue with AngularJS directives - encountering a problem with the property 'compile' being undefined

Just starting out with AngularJS and attempting to make a basic directive. Unfortunately, the code is throwing a TypeError: Cannot read property 'compile' of undefined. Any advice or suggestions would be greatly welcomed. JS var xx = angular.mo ...

Steps to implement an image zoom function triggered by a button click

I'm working on a school project that requires me to use only html, css, and javascript for creating a website. Currently, I'm designing a landing page with a button that will navigate the user to another page. My goal is to have the background im ...

What is the best way to add my ajax response data into a particular div element on the page?

I am facing a challenge with an ajax call that retrieves data and should insert it into a specific div box. The issue lies in the fact that I can only use one parameter in the success method to fetch the data, rather than multiple parameters. One potential ...

A Guide to Modifying Background Image Attribute using JavaScript

I am currently in the process of changing an attribute of a JavaScript variable from url("../images/video.png") (as declared in the CSS) to url("../images/pause.png") using this line of code: fullscreenPlayPauseButton.style.backgroundImage = "url("../imag ...

Guide to writing a unit test for a parameter decorator in NestJs

I want to implement a unit test for a basic custom decorator that I created, but I'm facing some challenges. This decorator was developed based on the solution provided here. I have Keycloak authentication set up and using this solution in my controll ...

Tips for resizing tab components in Materials-UI

I am currently developing a basic app that showcases heart rate, blood glucose levels, and other measurements. I am utilizing React and Redux for the development process and incorporating Materials-UI for the user interface. For displaying these metrics, ...

Have you ever wondered why the Chart is being added to the current div when employing ng-repeat?

I have successfully created a dynamic bar chart and placed it inside a div. However, when I try to achieve the same result using ng-repeat, the new chart is appended to the existing one. Below is my code: HTML: <div id="main" class="drop-container" ...

Find two separate solutions to the promise

I'm in the process of developing a promise-based route and here is my current promise implementation: const allowEdit = (postid, username) => { return new Promise((resolve) => { db.query(`SELECT * FROM post WHERE id = ${postid} AND usernam ...

The Plupload internal version seems to be incorrect. The file is labeled as 2.3.9, however, the actual version within the file is 2.3

We recently identified a security vulnerability issue with plupload 2.3.6 being deemed as vulnerable. To address this, we downloaded version 2.3.9 from the official Plupload website here: Upon inspection, we found that the zip file is labeled as 2.3.9, bu ...

The functionality of the UI Bootstrap custom directive controller does not seem to be recognized

I am trying to implement UI Bootstrap Collapse within my custom directive called <collapse> Unfortunately, I am encountering the following error: Error: [ng:areq] Argument 'CollapseDemoCtrl' is not a function, got undefined You can view m ...

I am not encountering any errors; however, upon entering the room, my bot fails to initiate creation of a new channel

const Discord = require("discord.js") const TOKEN = "I forgot to include my token here" const { Client, GatewayIntentBits } = require('discord.js'); const { MemberFetchNonceLength } = require("discord.js/src/errors/Erro ...

Unable to create selected buttons in Vue.js

I'm having trouble creating buttons that can select all options when clicking on either size or color. The buttons aren't showing up at all. Can someone help me identify the issue? I've attempted various solutions but none seem to work. Any ...

"Unleashing the Power of MongoDB's Dynamic $in

Is there a way to dynamically pass a list of strings to a $in clause in MongoDB? I attempted the following code, but it didn't work and I haven't been able to locate more information other than an example with hardcoded values. The restrictedUs ...