我有一组复选框,允许用户检查要分配给新用户的 Angular 色。我能够过滤并仅获取实际选中的复选框,但是,我无法找到仅返回这些选中复选框的“名称”键的最佳方法。
userToAdd.roles = this.roles.filter( (role) => role.checked );
有没有办法使用reduce,或者基本上只是在过滤器中说“role.name”,这样我就不会返回整个对象?我可以使用 for 循环来完成此操作,但我很好奇是否有更好的方法将名称键作为过滤器的一部分返回?
这是对象现在的样子,这是错误的:
{
"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"
}
这就是对象的外观,在 Angular 色数组中我只包含名称,而不是 ID 或检查的键:
{
"firstName": "testing",
"lastName": "testing",
"username": "testing",
"email": "testing",
"roles": [
"uma_authorization",
"offline_access"
],
"password": "pass"
}
最佳答案
过滤后即可进行映射。即:
userToAdd.roles = this.roles.filter( (role) => role.checked ).map(role => role.name;
关于javascript - Typescript 过滤并返回单个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60600552/