I am doing an APP in Angular 12. In my component.ts I have an string array[] like
AccessRoles["AA","BB"]
And on the other side I have a class like this
export class UserRole {
Id :string;
Active:boolean;
}
My class have this value UserRole
"UserRole": [
{
"id": "AA",
"Active": "false"
},
{
"id": "BB",
"Active": "false"
},
{
"id": "CC",
"Active": "false"
},
]
I need to set Active = true when element in UserRole
is in AccessRoles
I can do it using nested foreach, but is has low performance.
What I mean by bad performance, is the bad practice of using nested ForEach. Any solution that does not use nested ForAEach is acceptable.
As is mentioned as an answer,here it helps, but I need to have my object with the same count of records.. If I filter, I will loose those records where is Active is false.
What I need as answer is like this
"UserRole": [
{
"id": "AA",
"Active": "true"
},
{
"id": "BB",
"Active": "true"
},
{
"id": "CC",
"Active": "false"
},
]
Thanks
CodePudding user response:
You can use Set
to know if UserRole exists in the AccessRole to avoid nested loops. Try the following -
const accessRolesSet = new Set(AccessRoles /*your accessroles string array*/);
for(let r = 0; r < UserRole.length; r ) {
if(accessRolesSet.has(UserRole[r].id)) {
UserRole[r].active = true;
}
}
As suggested by others, the filter
will work but it will not set active = true.
Hope it helps.