vue.jscomputed-propertiesadvanced-search

advanced search with computed property vuejs


Hey guys I have a data property called searchQuery as well as a computed property that searches my both the item name and the keywordArray in the templateArray and returns the templates back. It works great. However Im trying to make it a little bit more robust. heres my computed property

  searchResults: function(){
      return this.filteredTemplateArray.filter((template)=>{
        return template.itemName.toLowerCase().includes(this.searchQuery.toLowerCase())
          || template.keywordArray.toString().toLowerCase().includes(this.searchQuery.toLowerCase());
      })
  }

each template is returned as an object that contains an array called keywordArray with in it. the object looks like this

0:Object
categoryArray:Array[0]
dateAdded:"2016-05-27 10:16:56"
id:"15"
itemId:"73076"
itemName:"Colorful Trans"
keywordArray:Array[2]
0:"Water"
1:"Sparkles"
projectPath:"M:/Projects/Generics/CreativeEngine/2016/ColorfulImageTrans-Scott/ColorfulImageTrans.aep"
renderTime:"30"
stillImageLocation:"12.90"
tested:"1"
thumbName:"COLORFULIMAGETRANS"

basically what I want to do is if it returns no results for template.keywordArray.toString().toLowerCase().includes(this.searchQuery.toLowerCase()) I want to search each word seperated by a space as if it were its own searchQuery. For instance right now if I type in sparkles I get a result. if I type in water I get a result but if I type in water sparkles no results are returned. if searchQuery has a space search the keywordArray for both water and sparkles.


Solution

  • someArray.toString returns array items separated by comma , so try to replace that comma by space as follow :

    template.keywordArray.toString().replace(","," ").toLowerCase().includes(this.searchQuery.toLowerCase());
    

    if the searched words are not in order you could use the following approach:

    this.searchQuery.toLowerCase().split(' ').every(val => {
      return template.keywordArray.toString().toLowerCase().split(',').filter(item => {
        return item.includes(val)
      }).length !== 0;
    })
    /***OR directly search in keywordArray***/
    this.searchQuery.toLowerCase().split(' ').every(val => {
      return template.keywordArray.filter(item => {
        return item.includes(val)
      }).length !== 0;
    })
    

    A sample code :

    var items = ["aaa", "bbb", "ccc", "ddd"]
    var s = "aaa bb"
    var f = s.split(" ").every(st => {
      return items.filter(item => {
        return item.includes(st)
      }).length !== 0;
    })
    console.log(f)