简体   繁体   中英

Typescript Filter and return single key

I have a set of checkboxes that allow a user to check which roles to assign to a new user. I am able to filter back and get only the checkboxes that are actually checked, however, I am having trouble finding the best way to just return the "name" key of those checked checkboxes.

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

Is there a way to use a reduce, or basically just say "role.name" in the filter so I don't return the entire object? I can do this with a for loop, but I'm curious if there is a better way to just return the name key as part of the filter?

This is how the object looks now, which is wrong:

{
  "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"
}

This is how the object should look, in the roles array i just include the name, not the ID or checked keys:

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

you could map after filtering. ie:

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

You can achieve this using array map() method and object destructuring like:

userToAdd.roles = this.roles.filter(({checked}) => checked).map(({name}) => name);

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Yes you can use reduce.

 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() would also works but with reduce you don't have to iterate over array twice.

如果您有 linq,这是另一种选择:

userToAdd.roles = from(this.roles).where(role => role.checked ).select(role =>role.name).toArray();

你也可以使用这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM