1👍
✅
Assuming that your data is a JSON array, you could generate labels and datasets as follows:
const labels = baseData[0].set_data.map(v => v.month);
const dataSets = [];
baseData.forEach(o => dataSets.push({
label: o.location,
data: o.set_data.map(v => v.value),
borderColor: o.color,
borderWidth: 1,
fill: false
})
);
Please have a look at the runnable code sample below.
const baseData = [{
location: "Apartment A",
color: "red",
set_data: [
{ month: 1, value: 3500 },
{ month: 2, value: 2700 },
{ month: 3, value: 1500 }
]
},
{
location: "Apartment B",
color: "blue",
set_data: [
{ month: 1, value: 1700 },
{ month: 2, value: 2800 },
{ month: 3, value: 3200 }
]
}
];
const labels = baseData[0].set_data.map(v => v.month);
const dataSets = [];
baseData.forEach(o => dataSets.push({
label: o.location,
data: o.set_data.map(v => v.value),
borderColor: o.color,
borderWidth: 1,
fill: false
})
);
new Chart('graph_by_usage', {
type : 'line',
data: {
labels: labels,
datasets: dataSets
},
options: {
responsive:true
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="graph_by_usage" height="90"></canvas>
Source:stackexchange.com