0

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

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Hi @Dekel, thanks for the jsfiddle. Made life easier. However the search is case sensitive. How to make it searchable regardless of CAPS or small letters. I tried making it toLowerCase but it stopped working can you update codes for me thanks :)
@Zee you should use toLocaleLowerCase on both the elements: item[key].toLocaleLowerCase().includes(this.filterValue.toLocaleLowerCase()). Another option is to use regex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.