Skip to content Skip to sidebar Skip to footer

How To Filtering Between Array Of Sub Arrays And Array Of Sub Arrays In Javascript?

I have got two arrays of objects. I want to filter data based on PermissionObj. This is coming from database. Here are arrays of sub-arrays in the permissionObj. const PermissionOb

Solution 1:

It is possible to use reduce method and apply logic to decide what data should be pushed:

const result = data.reduce((a, c) => {
   let filterObj = PermissionObj.permission.find(f => f[c.label]);
   if (filterObj) {
      if (c.value) {
         a.push(c);
      }
      if (c.content) {
         c.content = c.content.filter(f => filterObj[c.label]
             .some(s => s.value.toLowerCase() == f.value.toLowerCase()));
         a.push(c);
      }
   }
   return a;
},[])

An example:

constPermissionObj = {
   permission: [
   {
      "books": [
         {
            "label": "Can View",
            "value": "can_view"
         }
      ]
   },
   {
      "Journals": [
         {
            "label": "Can View",
            "value": "can_view"
         },
         {
            "label": "Can Create",
            "value": "can_create"
         }
      ]
   },
   {
      "deal": [
         {
            "label": "Can update",
            "value": "can_update"
         },
         {
            "label": "Can delete",
            "value": "can_delete"
         }
      ]
   }
 ]
};

const data = [
   {
      label: "books",
      value: "can_view"
   },
   {
      label: "deal",
      content: [
         {
         value: "can_update"
         },
         {
            value: "can_delete"
         },
         {
            value:"can_view"
         }
      ]
   },
   {
      label: "Articles",
   },
   {
      label: "Journals",
      content: [
         {
            value: "can_create"
         },
         {
            value: "can_view"
         },
         {
            value: "can_delete"
         },
         {
            value: "can_edit"
         }
      ]
   }
];


const result = data.reduce((a, c) => {
   let filterObj = PermissionObj.permission.find(f => f[c.label]);
   if (filterObj) {
      if (c.value) {
         a.push(c);
      }
      if (c.content) {
         c.content = c.content.filter(f => filterObj[c.label].some(s => s.value.toLowerCase() == f.value.toLowerCase()));
         a.push(c);
      }
   }
   return a;
},[])
console.log(result);

Post a Comment for "How To Filtering Between Array Of Sub Arrays And Array Of Sub Arrays In Javascript?"