【问题标题】:react chart js skip zero value month反应图表js跳过零值月
【发布时间】:2020-04-22 19:32:30
【问题描述】:

我有一个显示每月捐款的折线图。但是我有几个月没有捐款的记录。我的 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]

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

【问题讨论】:

  • 您好,看看我的回答,您希望它们是字符串还是整数?
  • 整数我的朋友
  • 更新了代码,见sn-p
  • 哇!伟大的。这解决了我的问题。谢谢@Rkv88-Kanyan
  • 请投票 ????????????????????????????

标签: reactjs chart.js


【解决方案1】:

使用这个

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多