Home > database >  Filtering with multiple variable in vue js
Filtering with multiple variable in vue js

Time:11-21

I am working on filtering a table in vue js. I have done filtering the table with name & date. But now I don't understand how to add another filter with them.

Here is a codepen link codepen

my computed property is like this---

filterItem() {
  let filterClient = this.selectedClient;
  let startDate = this.localizeDate(this.startDate);
  let endDate = this.localizeDate(this.endDate);
  let filterBranch = this.selectedBranch;

  const itemsByClient = filterClient
    ? this.salesReport.filter((item) => item.client_name === filterClient) && item.business_branch=== filterBranch)
    : this.salesReport;

  return itemsByClient.filter((item) => {
    const itemDate = new Date(item.date);
    if (startDate && endDate) {
      return startDate <= itemDate && itemDate <= endDate;
    }
    if (startDate && !endDate) {
      return startDate <= itemDate;
    }
    if (!startDate && endDate) {
      return itemDate <= endDate;
    }
    return true;
  });
},

It works when I give both name & business branch but I want to filter the data with or without name.

For example, If I select a client then the table shows the client. Now what I want is, when I select a branch(the other fields remains empty) then the table shows the rows associated with the selected branch

CodePudding user response:

Just set up your filter functions and chain them.

filterItem() {
  let filterClient = this.selectedClient;
  let startDate = this.localizeDate(this.startDate);
  let endDate = this.localizeDate(this.endDate);
  let filterBranch = this.selectedBranch;

  const myClientFilterFunction = (item) => filterClient
    ? item.client_name === filterClient
    : true;

  const myBranchFilterFunction = (item) => filterBranch
    ? item.business_branch=== filterBranch
    : true;

  const myDateFilterFunction = (item) => {
    const itemDate = new Date(item.date);
    if (startDate && endDate) {
      return startDate <= itemDate && itemDate <= endDate;
    }
    if (startDate && !endDate) {
      return startDate <= itemDate;
    }
    if (!startDate && endDate) {
      return itemDate <= endDate;
    }
    return true;
  };

  return this.salesReport
    .filter(myClientFilterFunction)
    .filter(myBranchFilterFunction)
    .filter(myDateFilterFunction);
}

To achieve a more complex logic, like filtering only for branches or for clients, just add the filter functions programatically, e.g.

  let report = this.salesReport;

  if(this.selectedClient) {
    report = report.filter(myClientFilterFunction);
  }

  if(this.selectedBranch) {
    report = report.filter(myBranchFilterFunction);
  }

  report = report.filter(myDateFilterFunction);

  return report;
  • Related