Search code examples
javascriptjsonvue.jsaxioscomputed-properties

Combine two computed properties into one


I have select box and a search field to filter through my data table. I created two computed properties - first one is a category filter that gets name and id from a get call and compares values with values from another call. Second computed property is for normal table search. How can I combine these two into one property so I can apply it on the table?

Computed:

computed: {
  filteredTableData() {
      if (this.selectedId !== null) {
          const filtered = this.tableData.filter(d => {   
              let mediaTypeJ = this.mediaTypeId.find(x => {
              return x.ID === this.selectedId;
          });  
      return d.mediaTypeName === mediaTypeJ.name;
      });
      return filtered
      }
  return this.tableData
  },

  searchFilter() {
      return this.tableData.filter (item => {
      return 
  item.name.toLowerCase().match(this.search.toLowerCase()) ||     
  item.level.toLowerCase().match(this.search.toLowerCase()) ||      
  item.house.toLowerCase().match(this.search.toLowerCase())
   });  
  },
 }

Html:

<tbody>       
    <tr v-for="(item, index) in filteredTableData">  
        <td>{{ item.name }}</td>  
        <td>{{ item.level }}</td>  
        <td>{{ item.house }}</td>  
    </tr>
</tbody>

Thanks!


Solution

  • Try this:

      searchFilter() {
          return this.filteredTableData.filter (item => {
            return 
              item.name.toLowerCase().match(this.search.toLowerCase()) ||     
              item.level.toLowerCase().match(this.search.toLowerCase()) ||      
              item.house.toLowerCase().match(this.search.toLowerCase())
          });  
      },
    

    Filter the filteredTableData as searchFilter, then use it in the template.

    <tbody>       
        <tr v-for="(item, index) in searchFilter">  
            <td>{{ item.name }}</td>  
            <td>{{ item.level }}</td>  
            <td>{{ item.house }}</td>  
        </tr>
    </tbody>