i have that Object with two lists inside.
const list = {
Operator: [
{
Login: 'login1',
PermissionGroup: '2',
Sub: '3',
},
{
Login: 'login2',
PermissionGroup: '3',
Sub: '2',
},
],
PermissionGroups: [
{
PermissionGroupId: '2',
GroupsName: 'Gestor',
PermissionLevel: 2,
},
{
PermissionGroupId: '3',
GroupsName: 'Lider',
PermissionLevel: 3,
},
],
};
In my redux, i have the "Sub" of the Operators. So what do I have to do...
Step 1: Get my Redux "sub" and find which Operator it is in
Step 2: Now that I have the Operator, I need to find which operator corresponds to the PermissionGroup, using the PermissioninGroup(into Operators) and the PermissionGroupId(into PermissionGroups)
This method does what I want (Ignore final return), How do I optimize this method? I didn't want to use two filters for this
const search = (sub) => {
const usuario = listaUsuarios.filter((element) => element.Sub === sub)[0];
const permissaoUsuario = listaPermissoes.filter(
(element) => element.PermissionGroupId === usuario.PermissionGroup
)[0];
return permissaoUsuario.PermissionLevel;
};
Personally, the current solution seems okay (of course, if it is confirmed that one only requires the 0-th element from .filter(), it may be preferrable to use .find() instead). Since OP has requested an alternate, the solution below (which is not my recommendation) may achieve the desired objective.
Code Snippet
const searchSub = (needle, {Operator, PermissionGroups}) => (
[...Operator, ...PermissionGroups].reduce(
(res, obj) => ({
...res,
...(
'Sub' in obj && obj.Sub === needle
? {foundSub: {...obj}}
: 'PermissionGroup' in res.foundSub &&
'PermissionGroupId' in obj &&
obj.PermissionGroupId === res.foundSub.PermissionGroup
? {matchedPermissionGroup: {...obj}}
: {}
)
}),
{foundSub: {}, matchedPermissionGroup: {}}
)
);
const list = {
'Operator': [{
'Login': 'login1',
'PermissionGroup': '2',
'Sub': '3',
},
{
'Login': 'login2',
'PermissionGroup': '3',
'Sub': '2',
}
],
'PermissionGroups': [{
'PermissionGroupId': '2',
'GroupsName': 'Gestor',
'PermissionLevel': 2,
},
{
'PermissionGroupId': '3',
'GroupsName': 'Lider',
'PermissionLevel': 3,
},
]
};
console.log(searchSub('2', list))
console.log(
'PermissionLevel: ',
searchSub('2', list)?.matchedPermissionGroup.PermissionLevel
);
Explanation
... spread operator to construct one array with elements from both Operator and PermissionGroups array.reduce() to iterate over this combined arraySub is found, track it in res objectPermissionGroupId is found, track that as wellres object will have elements from both Operator and PermissionGroups array that matched.NOTE
.find() in this context.