react count object properties in an array
Assuming that the data you fetched from API is stored in data
variable, you can try the following code to find the count of movie
media type in your data array:
const movies = data.filter(item => item.media_type === 'movie')),
moviesCount = movies.length;
You can also dynamically calculate count of every media_type
in your data array:
const mediaTypes = data
.map(dataItem => dataItem.media_type) // get all media types
.filter((mediaType, index, array) => array.indexOf(mediaType) === index); // filter out duplicates
const counts = mediaTypes
.map(mediaType => ({
type: mediaType,
count: data.filter(item => item.media_type === mediaType).length
}));
Then counts
will be something like this:
[
{
"type": "tv",
"count": 3
},
{
"type": "movie",
"count": 3
}
]
ok i found the solition. thank you to poohitan for answer. i solved it through his answer.
countType(type) {
const countTypes = this.props.movies.filter(movie => movie.media_type === type);
return countTypes.length;
}
and while i am rendering my tv results, i just call the method above with type. for example:
return (
<div>
movie count: {this.countType('movie')}
tv show count: {this.countType('tv')}
</div>
);