mapping an object to an array of multiple objects

You can easily do so using flatMap

const data = [{
   role:'admin',
   resource:['calendar','appraisal'],
   action:['create:any','read:any','update:any','delete:any']
 },
 {
   role:'user',
   resource:['calendar','appraisal'],
   action:['create:own','read:any','update:own','delete:own']
}];

const mapped = data.flatMap(({role, resource, action}) =>
                 resource.flatMap(resource => 
                   action.map(action => ({role, resource, action}))));

console.log(mapped)

However since is generic this is will create also the entries for appraisal. If you want to skip them you can easily do it after, with a filter:

const calendars = mapped.filter(({resource}) => resource === "calendar");

Of course you can also obtain the appraisals in the same way. This approach will also work for any other item you’ll add in resource array.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top