Filter an object in Typescript and retrieve a single key

Managing a set of checkboxes is essential in assigning roles to new users. While it's possible to filter and retrieve only the checked checkboxes, extracting just the "name" key poses a challenge. The current method involves filtering with a for loop which seems less efficient than using reduce or a simpler way to return the name key along with the filtered checkboxes.

userToAdd.roles = this.roles.filter( (role) => role.checked );

Is there a more streamlined approach that allows directly accessing the "role.name" within the filter function? Instead of returning the whole object, can we modify the structure to solely include the names of the checked checkboxes?

The incorrect object representation with unnecessary keys:

{
  "firstName": "sfsdfds",
  "username": "fdsfsdf",
  "lastName": "sdfsdfsdf",
  "email": "dsfsdfdsf",
  "roles": [
    {
      "ID": "ce97fb46-7e04-4a4f-b393-5a5492b558fb",
      "name": "admin",
      "checked": true
    },
    {
      "ID": "e89bacd2-4140-46a1-9a2b-0f85aa9f9ca0",
      "name": "offline_access",
      "checked": true
    }
  ],
  "password": "pass"
}

The ideal object format should only display the names within the roles array and omit unnecessary keys:

{
  "firstName": "testing",
  "lastName": "testing",
  "username": "testing",
  "email": "testing",
  "roles": [
    "uma_authorization",
    "offline_access"
  ],
  "password": "pass"
}

Answer №1

One method is to perform mapping after applying a filter. Here's an example:

user.roles = this.userRoles.filter( (role) => role.selected ).map(role => role.title);

Answer №2

To accomplish this task, you can utilize the array map() function along with object destructuring in the following manner:

userRoles = activeUsers.filter(({selected}) => selected).map(({roleName}) => roleName);

When we use the map() method, it generates a new array by executing a specified function on each element of the original array.

Answer №3

A great way to handle this is by using the reduce method.

    const data = {
      "firstName": "sfsdfds",
      "username": "fdsfsdf",
      "lastName": "sdfsdfsdf",
      "email": "dsfsdfdsf",
      "roles": [
        {
          "ID": "ce97fb46-7e04-4a4f-b393-5a5492b558fb",
          "name": "admin",
          "checked": true
        },
        {
          "ID": "e89bacd2-4140-46a1-9a2b-0f85aa9f9ca0",
          "name": "offline_access",
          "checked": true
        },
        {
          "ID": "e89bacd2-4140-46a1-9a2b-0f85aa9f9ca0",
          "name": "offline_access2",
          "checked": false
        }
      ],
      "password": "pass"
    }


let filtered = data.roles.reduce((acc, curr)=>{
 if(curr.checked) {
   acc.push({
    name: curr.name
   })
 }
 
 return acc;

}, []);

console.log(filtered);

.filter().map() can be used as well, but the reduce method saves you from iterating over the array multiple times.

Answer №4

In case you are using Linq, here is an alternative approach:

userToAdd.roles = this.roles.Where(role => role.checked).Select(role => role.name).ToArray();

Answer №5

Another option is to utilize the following code snippet:

this.roles.filter( (role) => role.checked )[0].anyPropert;

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

Press anywhere on the screen to conceal the AngularJS element

Attempting to create a toggle effect using 2 ng-click functions. One is bound to a button, the other to the body tag. The goal is for my content to show when the button is clicked and hide when anywhere on the body is clicked. However, it seems that Angul ...

Leveraging Scrapy/Selenium for populating fields and conducting searches on LinkedIn's advanced search page

Discover the URL for LinkedIn's advanced search feature: In my attempt to complete fields and submit a form on the LinkedIn advanced search page using Selenium with Python, I encountered a challenge. Whenever I try typing in information for fields l ...

How do I adjust the controls in Three.js to align with the previous camera position?

The three.js scene is equipped with W,A,S,D and left and right arrow controls, which allow for movement of the camera. However, the controls restrict the camera's movement to a fixed direction in the scene, rather than relative to its previous positio ...

What is the best way to create a compound query in Firebase?

I am working on a TypeScript script to search for a city based on its population... import { getFirebase } from "react-redux-firebase"; ... get fb() { return getFirebase(); } get fs() { return this.fb.firestore(); } getCollection(coll ...

Utilize a single JavaScript script to handle numerous HTML forms within the same webpage

I am currently facing an issue with a page that contains multiple forms needing the same JavaScript code. This specific code is designed to add more input fields to the form, which it does successfully. However, the problem lies in the fact that it adds in ...

Is there a way to dynamically alter the content depending on the index of the current slide using swiper.js?

Hi, I am new to utilizing the Swiper framework and so far, it has been one of the best sliders I have ever experienced. Currently, I am trying to establish a connection between 2 div tags - one tag holds the content of each slide while the other tag contro ...

The auto-play feature fails to function on iPhone devices when using Reactjs

I am currently working with Reactjs and Nextjs. I have a video on my website that is functioning properly on Android phones but not on iPhones. How can I resolve this issue? I have attempted the following code: <video loop autoplay='' muted> ...

Adding metadata fields to an existing Markdown file within TinaCMS

Is it feasible to enhance a Markdown file using TinaCMS by introducing new frontmatter fields? Instead of generating a brand new Markdown file, my goal is to modify the current one by appending new frontmatter fields. Currently, I am able to modify a sin ...

Tips for including extra items in a JSON String using Angular 2

function execute(req:any): any { var stReq = JSON.stringify(req); // Adding additional item "Cityname": "angular2City" inside req req.Cityname = 'angular2City'; } Now, how can I include the additional item "Cityname": "angular2C ...

Tips on preventing the opening of a new browser tab by using Ctrl + click

Hey there, I've got a list of products that can be selected using the Ctrl key. $(parentSelector).on("click", function (evnt) { evnt.stopImmediatePropagation(); var item = $(evnt.delegateTarget) ...

Why are static PropTypes used in ReactJS and do they offer any solutions or are they merely a recurring design choice?

While delving into the code base of a web application, I came across some static PropTypes that left me questioning their purpose and necessity. Here is a snippet of the code in question: static propTypes = { fetchCricketFantasyPlayers: PropTypes.fun ...

How can you incorporate TypeScript's dictionary type within a Mongoose schema?

When using TypeScript, the dictionary type format is: { [key: string]: string; } However, when I try to define a custom schema in mongoose, it doesn't work as expected. const users = new Schema({ [key: string]: String, }); I also attempted t ...

The icons from MaterializeCSS are not displaying correctly on the navbar within an Angular 7 project

Having an issue implementing MaterializeCSS Icons on the navbar. The arrow-drop_down icon is not displaying correctly, showing only text instead. Oddly enough, the icons render properly on other pages except for the app.component.html file. I attempted to ...

Disregard the JSON formatting and extract solely the values

After extracting data from an API, the format of the returned information looks like this: [{"id":21},{"id":22},{"id":24}] Next, I need to send this data to a database using a different API. However, the format for sending should be like this: [21,22,24] ...

Can a cross-browser extension be developed that integrates with a Python backend for a web application?

Present State I am currently in the initial stages of planning a web application that users will access through a browser extension designed as a horizontal navigation bar. My initial plan was to utilize Pylons and Python for this project, but I am uncert ...

What is the method for obtaining the total number of steps taken in a day (pedometer) exclusively for the current day on the

Is there a way to retrieve the total steps count for the current day only? The tizen.humanactivitymonitor.setAccumulativePedometerListener function allows me to access the accumulativeTotalStepCount, which represents the cumulative walking and running ste ...

Optimal approach for incorporating individual identifiers into a complex hierarchy of object arrays

I am looking to assign unique ids to an array of objects: For example: const exercises = [ { type: "yoga", locations: [ { name: 'studio', day: 'Wednesday' }, { name: 'home' ...

Here's how you can arrange a list starting with the first item and then searching for a specific string using md-autocomplete in

As a newcomer to angularJs, I am looking for ways to filter search results more efficiently. Check out this example here: https://codepen.io/anon/pen/mpJyKm I am trying to customize the search result by filtering based on query input. Specifically, I wan ...

Troubleshooting Angular Prerendering: How Conditional JavaScript Usage Can Lead to 'document is not defined' Error

Currently, I am utilizing Angular 15 in an attempt to pre-render a website for SEO optimization. It has come to my understanding that certain elements such as document and window are unavailable during pre-rendering since the code does not operate within a ...

Clicking to reveal a v-date-picker v-menu and automatically focusing on a v-text-field within it?

I implemented a date-picker component in my app following the instructions from Vuetify. To enhance usability for desktop users, I removed the readonly attribute to allow manual input. Now, desktop users can easily navigate through form fields using th ...