Home > database >  Filtering Javascript array of objects by account type
Filtering Javascript array of objects by account type

Time:10-04

I have a javascript array that contains objects which have a few properties of which there are some booleans. I want to take the user's account type and filter out the ones that don't apply to them. I've included the filter code I have tried however it isn't working because it is filtering out if only one of the if statements come true. I understand this but am unsure how to resolve it.

Filter code

if(acc_type != 'Admin') {
      this.items = this.items.filter((item) => {
        return item.admin != true
      })
    }
    if(acc_type != 'Manager') {
      this.items = this.items.filter((item) => {
        return item.manager != true
      })
    }

Some objects from array this filter are acting on

{ header: "Management", admin: true, manage: true },
    {
        title: 'Creation Form',
        to: '/management/creation-form',
        admin: true,
        manage: true,
    },
    {
        title: 'Management',
        to: '/management',
        admin: true,
        manage: true,
    },
    { header: "Settings" },
    {
        title: 'Account',
        to: '/settings/account',
        admin: true
    },
    {
        title: 'Billing',
        to: '/billing',
        admin: true
    },

CodePudding user response:

  this.items = this.items.filter((item) => {
    return acc_type != 'Admin' && item.admin != true && 
           acc_type != 'Manager' && item.manager != true
  })

CodePudding user response:

Simply turn around your logic to make it work.

If it is an 'Admin' account, every item having admin: true should be in the resulting list. If the account is is 'Manager', everything having manage: true should be in the resulting list.

if (acc_type === 'Admin') {
  this.items = this.items.filter(item => !!item.admin);
}
else if (acc_type === 'Manager') {
  this.items = this.items.filter(item => !!item.manager);
}

According to this, for 'Admin' accounts all entries will be in the resulting list, for 'Manager' accounts there will be only the first two entries.

Don't be confused by the !! - it's only a boolean conversion. For this example it can be omitted.

CodePudding user response:

From how I understand:

this.items = this.items.filter(function(item){
  if(acc_type == 'Admin')
    return item.admin || !item.manager
  else if(acc_type == 'Manager')
    return item.manager || !item.admin
  else // any other acct
    return !item.admin && !item.manager
})
  • Related