How to use filter() to search a JavaScript object

In a lot of modern web applications, the front-end ends up receiving query result as a JSON object and the result is then formatted on the client-side.  In this post, I am going to show how you can use the JavaScript ‘filter()’ method to filter the results in different ways.

In the above example, we start with seven user records. Attributes may include a first name, a last name, and an email address. The recordset is stored as an array of objects.  We then filter the result for two subsets.  We find users that are gmail users and users that do not have the last name of “Smith”.

If you look at the gmail filter, you will notice an additional condition that looks to see if the email address is defined.  That condition is there because Amy Thomas has no email address within the dataset.  If that condition was not there, the code would error out.

Leave a Reply

Your email address will not be published. Required fields are marked *