2

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!

2 Answers 2

3

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;
    });
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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.