1👍
✅
Here’s a code sample that illustrates how to convert the response
into the data (labels
and datasets
) required by chart.js.
const response = [
{
"mmyy":"2019-12",
"promocode":"promo1",
"amount":"2776"
},
{
"mmyy":"2020-01",
"promocode":"promo1",
"amount":"1245"
},
{
"mmyy":"2020-01",
"promocode":"promo2",
"amount":"179"
}
];
const labels = Array.from(new Set(response.map(c => c.mmyy))).sort();
const promocodes = Array.from(new Set(response.map(c => c.promocode))).sort();
const datasets = promocodes.map(pc => ({ label: pc, data: []}));
labels.forEach(l => {
for (let pc of promocodes) {
let city = response.find(c => c.mmyy == l && c.promocode == pc);
datasets.find(ds => ds.label == pc).data.push(city ? Number(city.amount) : 0);
}
});
console.log("labels: " + JSON.stringify(labels));
console.log("datasets: " + JSON.stringify(datasets, undefined, " "));
Please have a look at the following JSFiddle
Source:stackexchange.com