Reputation:
i have a line chart showing donations per month. however i have records showing with months without donations. my json data looks like this.
"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
}
]
which month represents for ex: 2 is february, 3 is march, 4 is april. now i still need to show that there is no donation came from the month of january.
this is my js file
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>
);
}
expected output for data[0,10,60,1556,0,0,0,0,0,0,0,0]
i still wants to push to array with zero donation_amount. any help would be much appreciated. thanks
Upvotes: 2
Views: 367
Reputation: 1332
use this
y=Array.from(Array(12)).fill(0);
content.map((item,i) =>{y[parseInt(item.month)-1]=parseInt(item.donation_amount)});
.
output example .
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);
Upvotes: 1