How can I get the number of objects that contain a certain value from an array?
Using componentDidMount
to get stored data in a Firestore db
as
componentDidMount() {
db.collection(`company/${this.props.userID}/campaigns`).onSnapshot(collection => {
const campaigns = collection.docs.map(doc => doc.data());
this.setState({
campaigns,
});
});
}
This mounts the data in this.state
but I would like to get the count value for each by their status
field. Here is an example below whereas I am trying to get the length
of entries for status
= active
draft
paused
.
class App extends React.Component {
constructor() {
super();
this.state = {
campaigns: [{
id: 1,
status: "draft",
},
{
id: 2,
status: "active",
},
{
id: 3,
status: "draft",
},
{
id: 4,
status: "paused",
}
]
};
}
render() {
const totalCampaigns = this.state.campaigns
const activeCampaigns = this.state.campaigns.filter(campaign => campaign.status === "active")
const draftCampaigns = this.state.campaigns.filter(campaign => campaign.status === "draft")
const pausedCampaigns = this.state.campaigns.filter(campaign => campaign.status === "paused")
return (
<div>
total {totalCampaigns.length}
Active {activeCampaigns.length}
Drafts {draftCampaigns.length}
Paused {pausedCampaigns.length}
</div>
);
}
}
ReactDOM.render( < App / > , document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Could you please help me understand what I am doing wrong or if there is a better method for this?
Use reduce
method on state.campaigns
and return an object
where the keys will be the status
and the value will be the number of occurrence of the status
let state = {
campaigns: [{
id: 1,
status: "draft",
},
{
id: 2,
status: "active",
},
{
id: 3,
status: "draft",
},
{
id: 4,
status: "paused",
}
]
};
let getCount = state.campaigns.reduce(function(acc, curr) {
if (!acc.hasOwnProperty(curr.status)) {
acc[curr.status] = 1
} else {
acc[curr.status] += 1
}
return acc;
}, {})
console.log(getCount)
render() {
const totalCampaigns = // here goes the the getCount
return (
<div>
Active {getCount.draft}
Drafts {getCount.active}
Paused {getCount.paused}
</div>
);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments