Reputation: 219
I am mapping an array of objects and rendering a div based on it.
Below is my code:
const App = () => {
const types = React.useMemo(() => {
return get(data, 'something.typesDetails', []);
}, [data]);
return (
{true &&
<div> header </div>
<div>
{types.map((t => {
return (
<div>{type.name}</div>
)
})}
</div>
}
);
}
Here is the types array:
const types = [
{
id: '1',
name: 'type1',
},
{
id: '2',
name: 'type2',
},
]
The above code works fine when data structure is like above.
But consider if types has value like so
const types = [
{
id: null,
name: null,
}
]
In this case, it will still map through types and display div. I don't want to display div element. How can I check if types value contains null or stop looping through types if it has value like above?
Upvotes: 1
Views: 2195
Reputation: 509
You can filter object inside of array and then map through them:
return (
{true &&
<div> header </div>
<div>
{types.filter(t => t.id != null && t.name != null)
.map((t => {
return (<div>{type.name}</div>)
})}
</div>
}
);
Upvotes: 0
Reputation: 89214
You can use filter
to remove elements with null values.
types = types.filter(x => !Object.values(x).includes(null));
You can also use Array#every
to check:
if(types.every(x => !Object.values(x).includes(null)){
//go ahead with mapping
}
Upvotes: 2