user2085143
user2085143

Reputation: 4232

Javascript Filter Refactor

I am filtering an array of objects using a function that looks like this

 var val = 'some text value'  

 this.someList = this.someList.filter(containsQuery);

        function containsQuery(listItem) {

        return   listItem.Key_One.toLowerCase().indexOf(val) > -1 ||
                 listItem.Key_Two.toLowerCase().indexOf(val) > -1 ||
                 listItem.Key_Three.toLowerCase().indexOf(val) > -1
        }

My question is what is a better way of filtering on each of the list item key values without having to write a new line for each one? i.e so I can avoid going

listItem.Key_Four.toLowerCase().indexOf(val) > -1
listItem.Key_Five.toLowerCase().indexOf(val) > -1

etc..

Any advice would be great.

Thanks!

Upvotes: 2

Views: 82

Answers (2)

Vic
Vic

Reputation: 43

Just a suggestion, array containing all the keys and loop them?

Like

var keys = ['key_one', 'key_two', 'key_three', 'key_four'];
for (i=0; i<keys.length; i++){
if (listItem[keys[i]].toLowerCase().indexOf(val) > -1) return true;
}
return false;

Ah damn, same idea as above, just took too long writing :D

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386560

You could use get keys of the object with Object.keys and iterate with Array#some.

function containsQuery(listItem) {
    return Object.keys(listItem).some(function (k) {
        return listItem[k].toLowerCase().indexOf(val) > -1;
    });
}

Upvotes: 3

Related Questions