reactjs - 反应图表js跳过零值月
问题描述
我有一个显示每月捐款的折线图。但是我有几个月没有捐款的记录。我的 json 数据看起来像这样。
"content": [
{
"donation_amount": "10",
"avg_donation_amount": 10.0,
"transaction_count": 1,
"month": 2
},
{
"donation_amount": "60",
"avg_donation_amount": 60.0,
"transaction_count": 1,
"month": 3
},
{
"donation_amount": "1556",
"avg_donation_amount": 97.00,
"transaction_count": 3,
"month": 4
}
]
例如,哪个月份代表:2 是 2 月,3 是 3 月,4 是 4 月。现在我仍然需要证明没有来自一月份的捐款。
这是我的 js 文件
async countDonationsPerMonth(){
let URL = BASE_URL+"donors_by_month";
let x = [];
let y = [];
let item = [];
try {
const response = await fetch(URL,{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bareer ' + this.getUserAuth()
}
})
const data = await response.json();
let content = data.content;
content.map((item, key) =>
y.push(item.donation_amount)
);
this.setState({
donation_amount: y
})
}catch(err){
console.log(err)
}
}
render() {
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
datasets: [
{
fill: false,
backgroundColor: 'rgba(75,192,192,0.4)',
borderColor: 'rgba(75,192,192,1)',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
data: this.state.donation_amount
}
]
};
return (
<div>
<Card title="Campaign Donations">
<Line
data={data}
width={150}
height={40}
/>
</Card>
</div>
);
}
数据的预期输出[0,10,60,1556,0,0,0,0,0,0,0,0]
我仍然想以零捐赠金额推送到数组。任何帮助将非常感激。谢谢
解决方案
用这个
y=Array.from(Array(12)).fill(0);
content.map((item,i) =>{y[parseInt(item.month)-1]=parseInt(item.donation_amount)});
.
输出示例。
content = [{
"donation_amount": "10",
"avg_donation_amount": 10.0,
"transaction_count": 1,
"month": 2
},
{
"donation_amount": "60",
"avg_donation_amount": 60.0,
"transaction_count": 1,
"month": 3
},
{
"donation_amount": "1556",
"avg_donation_amount": 97.00,
"transaction_count": 3,
"month": 4
}
];
y = Array.from(Array(12)).fill(0);
content.map((item, i) => {
y[parseInt(item.month) - 1] = parseInt(item.donation_amount)
});
console.log(y);
推荐阅读
- python - 为什么定义后不能更改函数的默认值?
- git - 在同一台机器上为不同的存储库使用不同的 git 用户
- sockets - ATWINC1500 SSL 套接字连接中止
- python-3.x - 二进制搜索函数在python中返回None值
- r-markdown - LaTeX 表示法导致错误“在编织 pdf_document 时,您可能需要在某个内联 R 表达式 `r ` 周围添加 $ $”
- python - 基于索引以块的形式迭代 df
- airflow - Apache Airflow:Dag 任务标记为僵尸,后台进程在远程服务器上运行
- c# - 如何使用 Entity Framework 刷新我的所有实体
- sql - SQL,通过移位列有效地连接同一个表
- java - RCP 无头应用