I would like to optimize a method which I use to decide which values to display in a tale. I have a table that shows different values, and on top of it, there are some input fields. The values selected in the input field are used to filter the content of the table.
<!-- the input fields-->
<v-select placeholder="Index" :options="indexList" v-model="filterTable['indexedValue']" @input="filteringTable"></v-select>
<v-select placeholder="Domain" :options="domainList" index="index" label="txt" v-model="filterTable['domainValue']" @input="filteringTable"></v-select>
<!-- table -->
<table>
<tbody>
<tr v-for="(value, i) in filteringTable()" :key="value.id">
...<!-- values shown here-->
</table>
The values selected in the input fields are bounded to the object filterTable.
data () {
return {
filterTable: {}
}
}
And the method that is called on input is defined as follows:
filterTable () {
var newLinks = this.links // object containing all the info we want to show in the table
if (this.filterTable['indexedValue'] != null && this.filterTable['indexedValue'] !== undefined) {
newLinks = newLinks.filter(l => l.post.indexed === this.filterTable['indexedValue'])
}
if (this.filterTable['domainValue']) {
newLinks = newLinks.filter(l => l.tag.domain === this.filterTable['domainValue'])
}
return newLinks
}
(my code has 2 more if statements that check value given by some other input fields, but they also follow the same logic above)
This code works and it does filter the table, but as you can see there are two many if statements in it and I am wondering if there are some ways I can follow to make it more efficient/optimized?
Any advice is highly appreciated!
Well its better to use computed here instead of methods. I also renamed your function because there could be a problem with the names because they are the same:
computed: {
filter_table() {
return this.filterTable["domainValue"]
? this.links.filter(l => l.tag.domain === this.filterTable["domainValue"])
: this.links.filter(
l => l.post.indexed === this.filterTable["indexedValue"]
);
}
};
<tr v-for="(value, i) in filter_table" :key="value.id">
This should do the job.
You also dont need things like var newLinks = this.links you can directly go with this.links.filter(). Filter returns you a new array with the filtered values.
Edit:
You said you want to filter if both conditions are met:
computed: {
filter_table() {
return this.links.filter(
(l) =>
l.tag.domain === this.filterTable["domainValue"] &&
l.post.indexed === this.filterTable["indexedValue"]
);
};