Verifying the presence of an object in an array based on its value using TypeScript

Having the following dataset:

roles = [
{roleId: "69801", role: "ADMIN"}
{roleId: "69806", role: "SUPER_ADMIN"}
{roleId: "69805", role: "RB"}
{roleId: "69804", role: "PILOTE"}
{roleId: "69808", role: "VENDEUR"}
{roleId: "69807", role: "SUPER_RB"}
]

The objective is to filter the table and check if there is an object containing a specific role value.

The function to achieve this would be as follows:

checkRoleExistence(role){

// Return true if role exists in any of the objects, else return false
}

To use it, one could call the function like this:

let ifExists = this.checkRoleExistence("PILOTE") ;

One idea for implementing this is to utilize the "filter" function from Ecmascript.

Any suggestions or improvements?

Answer №1

You have the option to utilize the some method along with destructuring.

let positions = [ {posId: "69801", position: "Manager"}, {posId: "69806", position: "Supervisor"}, {posId: "69805", position: "Analyst"}, {posId: "69804", position: "Developer"}, {posId: "69808", position: "Salesperson"}, {posId: "69807", position: "Consultant"} ]

const checkPositionPresence = posParam => positions.some( ({position}) => position == posParam)

console.log(checkPositionPresence("Manager"));
console.log(checkPositionPresence("Designer"));
console.log(checkPositionPresence("Analyst"));

Answer №2

An additional tip to consider alongside the answers provided here is utilizing the find() method to retrieve a value that meets your specific criteria.

const index = this.roles.findIndex(role => role.name === 'ADMIN');
if (index > -1) {
    const value = this.roles[index].roleId);
    }

This approach will return the roleId that aligns with your search query.

Answer №3

Here is a solution that may help you: click here to view

export class RoleComponent implements OnInit {
  roles: Role[] = [];
  isRoleExist:boolean = false;
  constructor() { }

  ngOnInit() {
    const data = this.getRoles();
    this.roles = JSON.parse(data);

    this.isRoleExist = this.checkRoleExistence('PILOTE');
    console.log(this.isRoleExist);
  }

  checkRoleExistence(roleLabel: string):boolean {
    return this.roles.some(r => r.roleLabel === roleLabel);
  }

  getRoles() {
    return `[
    {"roleId": "69801", "roleLabel": "ADMIN"},
    {"roleId": "69806", "roleLabel": "SUPER_ADMIN"},
    {"roleId": "69805", "roleLabel": "RB"},
    {"roleId": "69804", "roleLabel": "PILOTE"},
    {"roleId": "69808", "roleLabel": "VENDEUR"},
    {"roleId": "69807", "roleLabel": "SUPER_RB"}
    ]`;
  }
}

export class Role {
  roleId: number;
  roleLabel: string;
}

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

Starting Array index value at 1 in React js: A step-by-step guide

Is there a way to make the index value start from 1 instead of 0? {props.useraccountListData.useraccountTypeList.map((item, index) => ( {index} ))} The current output is starting from 0, 1, 2. However, I would like it to start from 1, 2, 3... ...

Verify if data already exists in an HTML table column using JavaScript

As a beginner in web programming, I am currently trying to dynamically add data to a table. But before inserting the data into the table, my requirement is to first verify if the data already exists in a specific column, such as the name column. function ...

Saving a single ID at a time in a UseState array by clicking in ReactJS

When clicking on the "click here" button, I am trying to save favorite post IDs in an array. However, the issue is that it is currently only saving one ID at a time in the array. Every time you click on another "click here" button, it removes the previous ...

Generating a d.ts file for images in Typescript using automation techniques

Currently, I am working on a React application that utilizes TypeScript and webpack. I am aware that in TypeScript, when importing an image file, it is necessary to create a d.ts file in the current directory and include the following code: // index.d.ts ...

PHP is unable to decode JSON that has been converted from JavaScript

When I send an array as a POST request, I first convert it to JSON using the JSON.stringify() method. However, I encountered an issue when trying to decode it in PHP. // JavaScript var arr1 = ['a', 'b', 'c', 'd', & ...

Transforming a value within a controller into a directive

I am uncertain if I am approaching this correctly, but my goal is to convert a piece of code from a controller to a directive. The reason for this change is that I want to reuse the code with different values without creating multiple large object literals ...

Modifying multiple heading tags simultaneously with jQuery

Currently utilizing jQuery to append a string to all heading tags (h1, h2,..., h6) and display it on the screen. Seeking guidance specifically for the replacing aspect, and open to solutions using plain javascript as well. The code I have so far, which I ...

Having trouble resolving an error while attempting to incorporate an npm module into a vanilla JavaScript application

I admit my lack of expertise in building modern JavaScript apps is becoming evident. Currently, we have a Capacitor app that uses plain JavaScript without any build tools, and it functions well. Our goal is to incorporate Microsoft Code Push support throu ...

Is there a way to trigger a function after a tooltip or popover is generated using Twitter Bootstrap?

Is there a way to manipulate a tooltip or popover with twitter bootstrap after it has been created? It seems like there isn't a built-in method for this. $('#selector').popover({ placement: 'bottom' }); For instance, what if I ...

How can I use Angular to dynamically open a video that corresponds to a clicked image?

I need assistance with a functionality where clicking on an image opens a corresponding video on the next page. The issue is that all images have the same ID, making it difficult to link each image to its respective video. Below is the data I am working ...

In an AngularJS custom filter function, the error message "keys is not defined" is displayed

As I was reviewing examples in an Angular JS book, I came across a concept that has left me puzzled. It involves the use of custom filters with ng-repeat. Below are the code snippets: <a ng-click="selectCategory()" class="btn btn-block btn-default btn- ...

Utilizing ngFor to iterate over items within an Observable array serving as unique identifiers

Just starting out with Angular and I'm really impressed with its power so far. I'm using the angularfire2 library to fetch two separate lists from firebase (*.ts): this.list1= this.db.list("list1").valueChanges(); this.list2= this.db.list("list2 ...

Code in jQuery or JavaScript to retrieve precise node information for the currently selected form field, text, or image on a webpage

Looking to retrieve specific information about the item that has been clicked on a web page using jquery. The clickable item could be a form element (like a checkbox, text box, or text area) or a section of text within a paragraph, div, list, or image... ...

Passing data between Angular v1 components

I'm facing an issue in Angular v1.6.1 where I am encountering difficulties transferring data from one component to another. The navbar component, located in app\common\navbar, has a controller that pulls data from a service. The following f ...

Implementing a Beveled Edge on a Shape using ThreeJS

I have put in a lot of effort to find the solution, but unfortunately I have not been successful so far. Currently, I am working on creating a shape using THREE.Shape, and I have the vertices data stored in a file. The shape appears to be straight without ...

When providing the index.html file using express.js, remember to include the user-agent header

When using my Express.js app to render my index.html page, I want to customize the http 'User-Agent' header. </p> <p>I've tried this method without success:</p> <pre><code>req.headers['user-agent'] = ...

Save the environment value within Vue when the app starts up

When working with a basic web app created using VueJS, the application makes an API call that returns an object containing the environment name. For instance: https://appsdev/mysimpleapp/api/environment returns {"applicationName":"My S ...

My webpage is experiencing issues with function calls not functioning as expected

I have created a select menu that is integrated with the Google Font API. To demonstrate how it works, I have set up a working version on JSBIN which you can view here. However, when I tried to replicate the code in an HTML page, I encountered some issues ...

Update the DOM if the index of any data elements have been modified

Can Vue.js detect the swapping of array elements in my data object? data: { list: [ 'Foo', 'Bar', 'Test' ] } This is the method I am using to swap entries: swapIndex: function(from, to) { var first = this ...

The flag will never turn true; it's stuck in the false position

Currently, I am in the process of developing a custom hook to store data on a server. To mimic the server call, I have implemented a simple setTimeout function that changes the value of the data creation flag to true after 2 seconds. I have a specific fun ...