1

I have an orbject array as data and I would like to have several select menus in order to filter the data and show it on screen in a reactive way. I have managed to get one filter to work, but the idea here is to be able to chain filters so that the result can be filtered by any combination of select vlaues.

I have broken down my code to a minimalistic example below :

<template>
  <div class="mp" style="width: 100vw;">
    <div class="col-2">
                <span class="lbl">FILTER1</span>
                <select v-model="selectedMA" class="form-select"  >
                <option value="">all</option>
                <option value="Germany">Germany</option>
                </select>
    </div>
    <div class="col-2">
                <span class="lbl">FILTER2</span>
                <select v-model="selectedMA2" class="form-select"  >
                <option value="">all</option>
                <option value="Tier1">Tier1</option>
                </select>
    </div>

    <p>DATA :</p>
    <p> {{actorListTest2}} </p>
  </div>  
</template>


<script >
import {onMounted, onBeforeMount, ref, computed, watch} from 'vue'
import getActorDocs from '../composables/getActorDocs'
export default {
setup(){

  const {actorDocs, loadActors} = getActorDocs()
  const selectedMA = ref("all")
  const selectedMA2 = ref("all")
  
  loadActors(); // load data
  var filteredActors = actorDocs

  const actorListTest2 = computed(() => {
    if(selectedMA.value == "all" && selectedMA2.value == "all"){return filteredActors}
    else{ 
      return filteredActors.filter(obj => {
        return obj.country == selectedMA.value
      }).filter(obj => {
          return obj.type == selectedMA2.value
      })}
    
    });


    return {filteredActors, actorListTest2, selectedMA, selectedMA2, actorDocs}
    }//setup
}
</script>


<style scoped>
</style>
JK2018
  • 429
  • 1
  • 9
  • 23

1 Answers1

0

Inspired by this post (Array filtering with multiple conditions javascript), I figured out a way to get it to work. Might not be the best way to do it , but it works

const actorListTest2 = computed(() => {
    if(selectedMA.value == "" && selectedMA2.value == ""){return filteredActors}
    else { 
      return filteredActors.filter(obj => {
        return (!selectedMA2.value.length || obj.type == selectedMA2.value)
        && (!selectedMA.value.length || obj.country == selectedMA.value)
    })}
    
    });
JK2018
  • 429
  • 1
  • 9
  • 23