Benoit Aspirault
Benoit Aspirault

Reputation: 33

Vue js - filter a table with multiple column

i'm quite a beginner so this i probably obvious to you guys but... I'm making a filter in Vue js 2.0 that filter in any column. I came up with this

    computed: {
    filteredAndSortedData() {
        let result = this.testData;
        if (this.filterValue) {
            result = result.filter(item =>                
item.round.includes(this.filterValue) ||
item.cat.includes(this.filterValue) ||
item.player1.includes(this.filterValue) ||                                                                  
item.player2.includes(this.filterValue));
        }

here the jsfiddle example: https://jsfiddle.net/ebxsvac0/ of what i'm trying to do.

My question is how do I rewrite this code without hardcoding the column variable. thank

Upvotes: 0

Views: 2594

Answers (1)

Dekel
Dekel

Reputation: 62536

You can use the following instead:

if (this.filterValue) {
    result = result.filter(item => Object.keys(item).map((key) => item[key].includes(this.filterValue)).includes(true));
}

For every item - go over all of the keys (they are the column names) and check for everyone if the item includes the value you want to filter in that column.

Here is the update to your jsfiddle:
https://jsfiddle.net/ebxsvac0/1/

Upvotes: 2

Related Questions