[Vuejs]-When using search filters in Vue JS is there a way to search against objects in the array?

1๐Ÿ‘

โœ…

Type in what you want to search no matter if name, location or grapes, if you type in for example shiraz it will display all elements that includes shiraz in name, location or grapes

let vue = new Vue({
  el: '#app',
    data() {
        return {
            search:'',
            products: [
              { 
                name: 'The Black Sock',
                location: 'Australia',
                grapes: ['shiraz']
              },
              { 
                name: 'Goat Roti',
                location: 'France',
                grapes: ['Shiraz' , 'Mourvedre']
              },
              { 
                name: 'Amon Ra',
                location: 'New Zealand',
                grapes: ['Chardonnay', 'Riesling']
              }
            ]
        }
    },
    methods: {
       sortByName(a,b){
          return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
       }
    },
    computed: {
        filteredProducts:function(){
           let comperator = this.sortByName;
           if(this.search == "") return this.products.sort(comperator);
           let search = this.search.toLowerCase();
           return this.products.filter(({name, location, grapes}) => name.toLowerCase().includes(search) || location.toLowerCase().includes(search) || grapes.find(el => el.toLowerCase().includes(search))).sort(comperator);
        }
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input type="text" v-model="search" placeholder="Search products">
  <ul>
      <li v-for="product in filteredProducts">
         <h2>{{product.name}}</h2>
        <p>{{product.location}}</p>
        <p>{{product.grapes}}</p>
      </li>
  </ul>
</div>

0๐Ÿ‘

You can use includes to check if something exists in the array or not.

You can use filter with includes like this.

const products = [
              { 
                name: 'The Black Sock',
                location: 'Australia',
                grapes: ['shiraz']
              },
              { 
                name: 'Goat Roti',
                location: 'France',
                grapes: ['Shiraz' , 'Mourvedre']
              },
              { 
                name: 'Amon Ra',
                location: 'New Zealand',
                grapes: ['Chardonnay', 'Riesling']
              }
            ]
            
const selectedGrapes =  'Shiraz'  

const filteredProducts = products.filter(product => product.grapes.includes(selectedGrapes))

console.log(filteredProducts)
    

Leave a comment