Cleaner way to filter data

63 views Asked by At

I have data that is in an array of structs. I don't have access to a query variable, and I need to filter down the data. So var I have

    arData = arData.filter(
        function(item){
            return (form.searchPhrase == "" 
                ||
                item.name CONTAINS form.searchPhrase
                ||
                item.company CONTAINS form.searchPhrase
                ||
                item.address CONTAINS form.searchPhrase
                ||
                item.address2 CONTAINS form.searchPhrase
                ||
                item.city CONTAINS form.searchPhrase
                ||
                item.state CONTAINS form.searchPhrase
                ||
                item.zip CONTAINS form.searchPhrase
                ||
                item.email CONTAINS form.searchPhrase
                ||
                item.tel CONTAINS form.searchPhrase
                );
        });

I am going over all the fields in item.

What I don't like about this is that it seems highly repetitive. It is likely that a new struct key could be added. Or an existing be removed. I am looking for a cleaner way to do this.

1

There are 1 answers

0
Alex On BEST ANSWER

Why not just loop over the item's properties then?

arData = arData.filter(
    function(item){
        if (form.searchPhrase == "") {
            return true;
        }
        for (itemProperty in item){
            if (isSimpleValue(item[itemProperty]) && item[itemProperty] CONTAINS form.searchPhrase) {
                return true;
            }
        }
        return false;
    });

In case your item might contain properties with a null value (for example if you read JSON from an external API), you want to check structKeyExists(item, itemProperty) in the loop as well.