Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading