Creating a sophisticated structure in real-time

Each user's permissions will vary based on their roles. My goal is to create an object structure like this:

let permissions = {
    'state': {
        'tool': ['subTool1', 'subTool2']
    }
}

Here is an example:

roles = ['NY_email_submit', 'NY_email_approve', 'NY_build_submit', 'NY_build_view', 'DC_email_submit']

let permissions = {
    'NY': {
      'email': ['submit', 'approve'],
      'build': ['submit', 'view']
    },
    'DC': {
      'email': ['submit']
    }
  };

I am iterating through a list named roles, which contains strings in the format of state_tool_subTool.

I want to avoid duplicates. For instance, if the next user role processed is NY_build_approve, I simply want to add approve to the list at ['build'].

At present, the following code snippet is not functioning correctly.

roles.forEach(role => {
    role = role.split('_');

    let state = role[0];
    let tool = role[1];
    let subTool = role[2];

    if ([state] in permissions) {
      permissions[state] = { [`${tool}`]: [subTool] };
    } else {
      //permissions[state][`${tool}`].push(subTool);
    }
  });

Answer №1

You're definitely headed in the right direction! Just a few more checks and you'll have it nailed down.

let accessLevels = {};
  
roles = ['NY_email_submit','NY_email_approve','NY_build_submit','NY_build_view', 'DC_email_submit'];

roles.forEach(role => {
    let [region, action, subAction] = role.split('_');

    if (region in accessLevels) {
      if (action in accessLevels[region]) {
        accessLevels[region][action].push(subAction)

      } else {
        accessLevels[region][action] = [subAction]
      }
      
    } else {
      accessLevels[region] = {[action]: [subAction]}
    }
});

console.log(accessLevels);

Answer №2

roles = ['NY_email_submit', 'NY_email_approve', 'NY_build_submit', 'NY_build_view', 'DC_email_submit']

let permissions = {};

roles.forEach(role => {
    role = role.split('_');

    let state = role[0];
    let tool = role[1];
    let subTool = role[2];

    if (!permissions[state]) { 
      permissions[state] = {[tool] : [subTool]};
    } else {
        if (permissions[state][tool]) {
          if(!permissions[state][tool].includes(subTool)) {
            permissions[state][tool] = [...permissions[state][tool], subTool];
          }
        }
        else {
          permissions[state][tool] = [subTool];
        }
    }
  });
console.log(permissions);

Answer №3

Check out this alternative method that utilizes the reduce function

roles = ['NY_email_submit', 'NY_email_approve', 'NY_build_submit', 'NY_build_view', 'DC_email_submit']
sp=roles.map(o=>o.split("_")).reduce((acc,curr)=>{
        if (!acc[curr[0]]) acc[curr[0]]={...acc[curr[0]],[curr[1]]:[...[curr[2]]]}
        else { 
          if(acc[curr[0]][curr[1]]) {         
          i=acc[curr[0]][curr[1]]
          acc[curr[0]]={...acc[curr[0]],[curr[1]]:[...i,...[curr[2]]]} }
          else  {acc[curr[0]]={...acc[curr[0]],[curr[1]]:[...[curr[2]]]} }

        }
         return acc
},{})
console.log(sp)

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

Rendering data from the server using backbone.js: A comprehensive guide

Initially, this is the response received from the server $response = array(); $i = 0; while($result = mysql_fetch_assoc($query)){ $response[$i]["id"] = $result["ID"]; $response[$i]["post_ ...

The variable req.body.Dates has not been declared

I am currently working on a project that involves dynamically populating two drop down menus using SQL Server. Depending on the selected items, I need to load a specific ejs template using AJAX. My goal is to load data based on the selected criteria. For e ...

Upon returning, the C string function argument is found to be NULL

Currently, I am working on a function that needs two strings as inputs and returns two different strings as outputs. My approach was to use an int for the error code and have two pointers to C strings as arguments. This is how I implemented it: int anneal ...

Encountering a peer invalid error message while using npm

As I work on integrating swagger-ui into an existing project, I encounter the following error messages: Olivers-MacBook-Pro:incrementum oliverpike$ npm install --save-dev --save-exact <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfem ...

What steps should I take to effectively execute lazy loading for my specific situation?

My challenge involves working with an array of 1000 users. I want to display these users in batches of 50 as the user scrolls through the page. The initial load should show the first 50 users, and more should be loaded as the user reaches the end of the sc ...

Dealing with 404 errors: The role of Nuxt.js and the srcDir option in handling URL

By incorporating the srcDir option into my nuxt.config.js file, I made the decision to transfer the pages, components, and layouts folders to the src directory. Below is how my configuration looks: module.exports = { srcDir: 'src', head: { ...

Display PDF in Forge Viewer using PDF Extension - warning generated by pdf.worker.js

Whenever we attempt to display a PDF file using our own API, the pdf.worker.js generates a warning message and the PDF always appears completely white. https://i.stack.imgur.com/IqGML.png All I can see is this (it's a wide PDF that renders fine in t ...

Issue with capturing mouse position in canvas when hovering over <h1> element above it

I am working on a project using React Three Fiber to animate a 3D model that follows the mouse cursor. However, I have noticed that when the mouse hovers over some divs or headings on top of the canvas element, the animation freezes and becomes choppy unti ...

Observing the state object in Pinia does not trigger when the object undergoes changes

I am facing an issue with setting a watcher on a deeply nested object in my Pinia state. export const useProductStore = defineStore("product", { state: () => ({ attributes: {}, }), }); When the object has data inside it, it looks something like ...

Whenever I attempt to start the server using npm run server, I encounter the following error message: "Error: Unable to locate module './config/db'"

This is the server.jsx file I'm working with now: Take a look at my server.jsx file Also, here is the bd.jsx file located in the config folder: Check out the db.jsx file Let me show you the structure of my folders as well: Explore my folder structur ...

The height of the div container exceeds 100% stretch

I am trying to incorporate a scrollbar for a specific div container. Here is the current code snippet that I have: $(document).ready(() => { for (let i = 0; i < 100; i++) { const newDiv = (`<div>Log Item</div>`); $("#logsCont ...

Having trouble with Node.js child_process.exec when the command doesn't return any output?

Recently encountered an issue while using child_process.exec in nodejs. The problem occurs when the command returns nothing. Here is what I did: const {exec} = require('child_process'); const cmd = `ps -ef | grep -v grep | grep abc123.py`; exec ...

Navigating the world of Arrays in MASM Assembly: A beginner's journey filled with

I'm a bit puzzled by a basic question: How does one go about populating arrays in assembly language? While high-level programming languages have for-loops to assign values to each index, I'm unsure about how to achieve the same task in assembly. ...

What is the best way to remove or reset a map from a material skybox in three.js?

In my ThreeJS scene, I am trying to implement different modes for viewing all models in the skybox, with or without textures. I have two functions called 'getSkyTexture' and 'getSkyColor' which are supposed to work separately. However, ...

Is using $window.location.reload(true) the same as manually pressing CTRL+F5?

I'm working on developing a feature called "version updated" component that displays a banner notifying users when the website has been updated and prompts them to reload. The challenge I'm facing is that some users are experiencing issues with c ...

A guide on elegantly pausing for the completion of .map() function and generating fresh keys within the array[index]

I am currently working on generating an array with the following values: { name: 'John', age: 35, employer: 'ABC', paycheck: 5,000, last_paycheck: 4,900, change: 100 } // new array and initializing the array with these initial values: ...

"Error message encountered while trying to execute a GET HTTP request with incorrect JSON formatting

Currently, I am working on retrieving a list of users from our software. The goal is to format the names and email addresses of these users into a list for comparison with other data sets in order to determine accuracy. I have included the code snippet I a ...

Align the reposition button with the pagination in the datatables

I am looking to adjust the placement of my buttons. The buttons in question are for comparison, saving layout, and printing. I would like them to be inline with the pagination, as I am using datatables here. <table id="sparepart_id" cellspacing="0" ...

Using vue.js to sort comments based on the highest number of votes

Can someone guide me on sorting data (comments) based on the number of votes using vue.js? Much appreciated! data: { comments: [{ title: "Excellent blog post!", votes: 5 }, { title: "Interactive commenting feature in VueJ ...

React: Unexpected behavior when modifying a variable's state using post-increment

When I utilize the post-increment operator to change the state variable, the count variable retains its old value... Allow me to illustrate this with an example app: When I click the button with the following code, the app displays the following sequenc ...