how to remove empty array length in javascript

Viewed 64

I have got an object . I need to get remove array of objects property if it's empty . For. example, test and books will be removed and give other values .

const PermissionObj = {
   permission: [
    {
      "test": []
   },
   {
      "books": []
   },
   {
      "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"
         }
      ]
   }
 ]
};

I am using double loop for solving this , but I am really trouble with this

3 Answers

Use filter() to use the condition, and Object.value() to transfer Object to Array

const result = PermissionObj.permission.filter(x => Object.values(x)[0].length !== 0);

  const PermissionObj = {
    permission: [
      {
        test: []
      },
      {
        books: []
      },
      {
        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 a = PermissionObj.permission.filter(x => Object.values(x)[0].length !== 0);
  console.log(a);

Use javascript filter function on your Permissions array to obtain the desired array of your interest

If I understood correctly:

const filteredPermissions = PermissionObj.permission
    .filter(p => Object.keys(p).some(k => p[k] && p[k].length));

Related