Utilize Angular to dynamically assign values from object properties to an array of objects based on property names

In my array of objects, there is a property named "modulePermissions" inside an array of objects called "tabList". I have another object called "moduleName", which has the same value as the "modulePermissions" name, and a boolean value has been assigned to it. Now, we need to check for the value of "modulePermissions" in the "tabList"; if it matches with the moduleName property name, then the boolean value of the moduleName property should be assigned to the "enableTabs" property in the "tabList".

Ts:

  moduleName = {
        Details: true,
        "Basic Info": true,
        "Captive Info": true,
        "Users": true,
        "Settings": true,
        "Restrictions": true,
        "Agents Group View": true,
        "W9": true,
        "EO": true,
        "License": true,
        "ACH": true,
        "Contacts": true,
        "Uploads": true,
        "Notes": true,
        "Tasks": true,
        "History": true,
        "Commissions": true
      }

tabList = [
    { name: 'Details', class: 'active', active: false, href: 'basic', tabEvent: '_detailsTab', id: 1, enableTabs: false,modulePermissions:'Details' },
    { name: 'W-9', class: '', active: false, href: 'w9', tabEvent: '_w9Tab', id: 2, enableTabs: false,modulePermissions:'W9' },
    { name: 'E&O', class: '', active: false, href: 'eo', tabEvent: '_eoTab', id: 3, enableTabs: false,modulePermissions:'EO'},
    { name: 'License', class: '', active: false, href: 'license', tabEvent: '_licenseTab', id: 4, enableTabs: false,modulePermissions:'License' },
    { name: 'ACH', class: '', active: false, href: 'ach', tabEvent: '_achTab', id: 5, enableTabs: false,modulePermissions:'ACH' },
    { name: 'Contacts', class: '', active: false, href: 'contacts', tabEvent: '_contactsTab', id: 6, enableTabs: false,modulePermissions:'Contacts' },
    { name: 'Uploads', class: '', active: false, href: 'uploads', tabEvent: '_uploadTab', id: 7, enableTabs: false,modulePermissions:'Uploads' },
    { name: 'Notes', class: '', active: false, href: 'notes', tabEvent: '_notesTab', id: 8, enableTabs: false,modulePermissions:'Notes' },
    { name: 'Tasks', class: '', active: false, href: 'tasks', tabEvent: '_taskTab', id: 9, enableTabs: false,modulePermissions:'Tasks' },
    { name: 'History', class: 'link-disabled', active: false, href: 'history', tabEvent: '_historyTab', id: 10, enableTabs: false,modulePermissions: 'History'},
    { name: 'Commissions', class: '', active: false, href: 'commission', tabEvent: '_commissionTab', id: 11, enableTabs: false,modulePermissions:'Commissions' }
  ]

I attempted to achieve this by using the following code:

getValue(){
   for (let i = 0; i < 16; i++) {
                this.tabList[i]['modulePermissions'] == userPermissions.moduleName.this.tabList[i]['modulePermissions'];
                this.tabList[i]['enableTabs'] = userPermissions.moduleName.this.tabList[i]['modulePermissions']
              }
}

Answer №1

This code snippet demonstrates a method I plan to implement:

for (let j = 0; j < listLength.length; j++) {
    let item = tabList[j];
    if (itemName[item.itemPermissions] !== undefined) {
        item.showTabs = itemName[item.itemPermissions];
    }
}

Answer №2

To cycle through tabList, you can utilize the Array.prototype.map method (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map).

For checking the existence of a specific property, you can employ Object.prototype.hasOwnProperty (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty).

A feasible solution may look like this:

const updateTabList = () => {
    return tabList.map((tabEntry) => {
        if (Object.prototype.hasOwnProperty.call(modName, tabEntry.perm)){
            const tabsEnabled = modName[tabEntry.perm];
            return {...tabEntry, ...{tabsEnabled}}
        }
        return tabEntry
    })
}

Note: This code snippet assumes that both modName and tabList are in scope.

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

Modifying the display toggle functions

How can I toggle between a button and an input type "file" when clicked? I am using jQuery to show and hide elements, but I need help changing back to the button when clicking somewhere else on the page. HTML: Upload<input type="button" id="upload" /& ...

Increasing the CPU usage of Chrome can be achieved by optimizing certain settings within the browser

Recently, I created an AI using NeroEvolution that plays the game of snake in p5.js. To enhance the training process, I am attempting to increase the number of game cycles per frame, but Chrome seems to be struggling to keep up with the demand. Is there ...

Prevent the change event from firing when the page loads in JavaScript - what can be done to avoid

Dealing with a form that contains chained select boxes can be quite challenging. Particularly when the Zend controller is involved in setting default values for these select boxes, which are pulled from the database. As someone who is new to jQuery, naviga ...

My ng-view html is unexpectedly displaying as plain string. What steps should I take to resolve this issue?

Why is my ng-view HTML displaying as plain text? How can I resolve this issue? I have encountered an error, here is the screenshot for reference: Unfortunately, I am unable to upload images at the moment. ...

Having trouble sending the request body via next-http-proxy-middleware

Recently, I've been attempting to develop a frontend using nextjs that communicates with a Java backend. To achieve this, I'm utilizing the npm package next-http-proxy-middleware. However, it seems like either my request body is getting lost in t ...

Tips for transferring all attributes from an Angular component to a template

I have a unique custom Angular 4 component where I utilize <img> as a template. The component is identified by the selector i-image, resulting in it being displayed in the UI as shown below: <i-image _ngcontent-c0="" alt="this is alt" ng-reflect- ...

sending properties to dynamically loaded components

I'm struggling with transferring props between children and parent components using Vue Routes. Within my Layout component, I have a wrapper DIV structured like this: <template> <div class="container" v-bind:class="cssClass ...

One of the components in React failed to render even though data was successfully passed to both

I utilized React to create a submenu list. The parent component receives JSON data and passes it down to two child components. However, only one of the child components successfully displays the data while the other fails to do so. Both child components ...

Guide on incorporating CSS into a JavaScript function

Currently, I am utilizing a jQuery monthly calendar where each day is represented by a cell. When I click on a cell, I can trigger an alert message. However, I also want to modify the background color of the specific cell that was clicked. Unfortunately, ...

Discovering latitude and longitude coordinates from a map URL, then enhancing dynamism by utilizing the coordinates as parameters

Hello, I am currently learning Vue.js and have encountered a challenge with embedding Google Maps URLs. Despite my extensive research on Google, I have not been able to find the solution I need. Here is an example of the URL I am working with: "https: ...

Error encountered: Invalid date within foreach loop

I'm perplexed as to why one date is considered valid while the others are labeled as "Invalid Date". const blocksDate = document.querySelectorAll(".roadmap__time"); blocksDate.forEach((block) => { const dateString = block.innerHTML; const da ...

Ensure that enums in Typescript are initialized explicitly

Is there a way to explicitly initialize the following enum in typescript? enum BloodGroup { OPositive = "O +ve", ONegative = "O -ve", APositive = "A +ve", ANegative = "A -ve", } I attempted something like this (I know it won't wo ...

Trigger on the cancellation or completion of a nested observable

I'm seeking a way to detect if an inner observable was not successfully completed (due to everyone unsubscribing) and then emit a value in that scenario. Something akin to defaultIfEmpty, but the current solution isn't effective. A trigger exis ...

Learn how Angular 2 allows you to easily add multiple classes using the [class.className] binding

One way to add a single class is by using this syntax: [class.loading-state]="loading" But what if you want to add multiple classes? For example, if loading is true, you want to add the classes "loading-state" and "my-class". Is there a way to achieve t ...

Calculate the height of the document in Python by using the function $(document).height()

I am looking to retrieve the height of a document for different URLs, essentially creating a JavaScript function similar to $(document).height() that works across all pages. Any suggestions on how I can accomplish this task? I have experience with Python ...

Conceal Bootstrap Toast for a day following dismissal

I have implemented Bootstrap 5 toasts to showcase an advertisement on my website. The goal is to make the advertisement disappear for 24 hours once the user closes it. Here's the current code snippet: <div class="position-sticky bottom-0" ...

Facing issues connecting to my MongoDB database as I keep encountering the error message "Server Selection Timed Out After 3000ms" on MongoDB Compass

I am encountering an error on my terminal that says: { message: 'connect ECONNREFUSED 127.0.0.1:27017', name: 'MongooseServerSelectionError', reason: TopologyDescription { type: 'Single', setName: null, maxS ...

express has a req.body that is devoid of any content

When making a request to my local server in my React app, the code looks like this: fetch("http://localhost:4000/signup", { method: "POST", mode: "no-cors", body: JSON.stringify({ name: "Joe", lname: "Doe& ...

I believe there may be a gap in the communication between TypeScript, JavaScript, Angular, Nginx, Alpine, and Docker within the network using Nginx. I am

After transitioning to Docker in order to create a virtual network to mimic a real network (using a bridge type with DNS that resolves the FQDN correctly to the corresponding IP), I encountered the following errors in the console.log - no data is being dis ...

In search of assistance with a persistent react.js error plaguing my work

I keep encountering an error whenever I run npm start on a new project. Does anyone have any insight on how to resolve this issue? The problem might lie within the project dependency tree rather than being a bug in Create React App. Here is what you can ...