如何从数组中获取包含一定值的对象数?
使用componentDidMount
作为在Firestore db
中的存储数据
componentDidMount() {
db.collection(`company/${this.props.userID}/campaigns`).onSnapshot(collection => {
const campaigns = collection.docs.map(doc => doc.data());
this.setState({
campaigns,
});
});
}
这会将数据装载到this.state
中,但是我想通过它们的status
字段获取每个计数值。这是下面的示例,而我尝试获取length
= status
active
draft
的{{1}}个条目。
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"));
能否请您帮助我了解我做错了什么,或者是否有更好的方法?
答案 0 :(得分:5)
在reduce
上使用state.campaigns
方法并返回一个object
,其中的键将是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>
);
}
答案 1 :(得分:4)
您可以使用以下代码
campaigns_1 = campaigns.reduce(function(acc, cur){
if(!acc[cur.status]) {
acc[cur.status] = []
}
acc[cur.status].push(cur);
return acc;
}, {});
现在 campaigns_1 将采用
的形式 {
"draft": [ {
"id": 1,
"status": "draft"
},
{
"id": 3,
"status": "draft"
}],
"active": [{
"id": 2,
"status": "active"
}],
"paused": [{
"id": 4,
"status": "paused"
}]
}
现在可以获取状态为草稿的元素数量
const = no_of_draft_campaigns = campaigns_1.draft.length;
const = no_of_active_campaigns = campaigns_1.active.length;
const = no_of_paused_campaigns = campaigns_1.paused.length;
您将获得的好处是,当您希望所有具有特定状态的元素都可以通过
获得时const draft_campaigns = campaigns_1.draft;
const active_campaigns = campaigns_1.active;
const paused_campaigns = campaigns_1.paused;
您可以在此处查看有效的示例