Home > database >  I want to get only roleId of those data that satisfies the condition (resourceId==3 && canView);
I want to get only roleId of those data that satisfies the condition (resourceId==3 && canView);

Time:04-08

I have this set of data:

roles = [{roleId:1,resourceRole:[
{canAdd:true,canUpdate:true,canView:true,canDelete:true,resourceId:1},
{canAdd:true,canUpdate:true,canView:true,canDelete:true,resourceId:2},
{canAdd:false,canUpdate:false,canView:false,canDelete:false,resourceId:3}
]},
{roleId:2,resourceRole:[
{canAdd:true,canUpdate:true,canView:true,canDelete:true,resourceId:1},
{canAdd:false,canUpdate:false,canView:false,canDelete:false,resourceId:2},
{canAdd:false,canUpdate:false,canView:false,canDelete:false,resourceId:3}
]},
{roleId:3,resourceRole:[
{canAdd:true,canUpdate:true,canView:true,canDelete:true,resourceId:1},
{canAdd:false,canUpdate:false,canView:false,canDelete:false,resourceId:2},
{canAdd:true,canUpdate:true,canView:true,canDelete:true,resourceId:3}
]}
];

In this case, my output should be [1] because resourceId==3 && canView==true is only in the data with roleId 1 and 3. How can I get this with minimum complexity?

CodePudding user response:

You can filter the roles if resourceId === 3 && canView, then map the results to get only the roleId:

const result = roles
  .filter(({ resourceRole }) =>
    resourceRole.some(({ resourceId, canView }) => resourceId === 3 && canView)
  )
  .map(({ roleId }) => roleId);

It returns only role 3 because is the only one that satisfies the condition resourceId === 3 && canView

Codesandbox: https://codesandbox.io/s/flamboyant-murdock-k70xvp?file=/src/index.js:1545-1549

  • Related