首页 > 解决方案 > 反应图表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]

我仍然想以零捐赠金额推送到数组。任何帮助将非常感激。谢谢

标签: reactjschart.js

解决方案


用这个

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);


推荐阅读