Skip to content
Advertisement

How to filter object array in React

JavaScript

I want to filter movies by genre and country. I can do that in a very weird method. But I wonder what’s the shortcut of filtering. Is there any option that I can filter if the prop or props exist, if not leave the original?

JavaScript

Advertisement

Answer

Rearrange your data in a way that allows you to enter a single value or object which can be used to filter the data in the movies. For example if you’d arrange your filter like this: (which you kind of already if you wouldn’t destructure)

JavaScript

Then you could loop over each movie and use the properties of the filters to access only the properties of a movie that you would like to check, like the pseudo-code below.

JavaScript

When doing this you can leave out, or add any filter that you’d like.

Do be aware that in the current state the snippet below assumes that it only has to work with an array.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement