Home > Back-end >  use filter only if an attribute exists with map function
use filter only if an attribute exists with map function

Time:10-30

Hello I am using filter with map in react.

props.types.filter(data => (data.is_active === 1)).map((data, index) => {
// some code.

});

I am getting props.types in this component. But sometimes props.types does not contain is_active property. So in that case, map function doesn't return anything. I want to run filter only when data.is_active property exists.
How do I do this ?

UPDATE 1:
As I said above I want to run filter only if is_active is exists but I will always run map.

CodePudding user response:

You can add conditional operator "?" after your filter method.

props.types.filter(data => (data.is_active === 1))?.map((data, index) => {
// some code.

});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Add a condition to your filter that checks if is_active is not set.
This way your map will always be executed, except when is_active is not 1.

props.types
  .filter((data) => data.is_active === undefined || data.is_active === 1)
  .map((data, index) => {
    // some code.
  });
  • Related