B-Ray
B-Ray

Reputation: 471

Filtering JavaScript Array of Objects With Value of Key Blank

I have an HTML form where different input text boxes are bound to an AngularJS search object, i.e.,

<input ng-model="search.state_prov">State</input>
<input ng-model="search.zip">Zip</input>
<input ng-model="search.country"></input>

I have a very large array of objects such as:

places = [{name: place1, state_prov: MO, zip: 63101, country: US},
   {name: place2, state_prov: CA, zip: 90210, country: US},
   {name: place3, state_prov: AB, zip: T0A, country: CA}
   {name: place4, state_prov: CA, zip: 90001, country: US}
]

I am trying to filter this array (search) based off the entered input in the form. When the form is initialized, the "search" object is empty. Once the user starts to type in the text box, say state_prov, the search object acquires a new key for search.state_prov with a value of whatever is typed in the box.

I can then search for matches in the places array, which I've been able to do using this array.filter() prototype:

var result = places.filter(searchQuery, query);

function searchQuery(place){
   return Object.keys(this).every((key) => place[key] === this[key]);
}

My issue is if the user fills in two text boxes, and then clears out one of them hoping to search by only the text box that still contains data, the "search" object will still have a key for the erased input with a value of empty string.

 search = {state_prov: "CA", zip: ""}

The filter will try to match objects in the array with an empty string when I would prefer to ignore this key altogether and only search for the key with a value associated with it. How can I get to this last step?

Upvotes: 1

Views: 69

Answers (2)

tklg
tklg

Reputation: 2642

You can check to see if the value at that key is not empty:

function searchQuery(place){
   return Object.keys(this).every((key) => place[key] === this[key] && this[key]);
}

because "", 0, null, and undefined evaluate to false.

Upvotes: 1

Georgy
Georgy

Reputation: 2462

What about (place[key] === this[key]) || (this[key] === '')? Or, if you do not need to check if strings are strictly equal, use String(place[key]).includes(this[key]).

Upvotes: 0

Related Questions