3๐
โ
I got the answer with help from Nina Scholz.
function getDataset(index, data) {
return {
label: 'Label '+ index,
fillColor: 'rgba(220,220,220,0.2)',
strokeColor: 'rgba(220,220,220,1)',
pointColor: 'rgba(220,220,220,1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(220,220,220,1)',
data: data
};
}
array.forEach(function (a, i) {
lineChartData.datasets.push(getDataset(i,JSON.parse(a)));
});
console.log(lineChartData);
Created a function getDataset within the parent function and iterated it using array.forEach function.
Thank you Nina for your help.
7๐
You could use a loop (Array#forEach
) and assign the parsed items (JSON.parse
) of the array.
var lineChartData = { labels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'], datasets: [] },
array = ["[0,0,0,0,0,0,0,0,0,0,0,0,0,58,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]", "[0,0,53,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]", "[0,0,381,0,0,649,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]"];
array.forEach(function (a, i) {
lineChartData.datasets.push({
label: 'Label ' + i,
fillColor: 'rgba(220,220,220,0.2)',
strokeColor: 'rgba(220,220,220,1)',
pointColor: 'rgba(220,220,220,1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke:
'rgba(220,220,220,1)',
data: JSON.parse(a)
});
});
console.log(lineChartData);
-1๐
Ninas answer completely worked
<div>
<canvas id="myChart"></canvas>
</div>
@section Scripts{
<script>
var lineChartData = {
labels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'],
datasets: []
},
array = [
"[0,0,0,0,0,0,0,0,0,0,0,0,0,58,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]",
"[0,0,53,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]",
"[0,0,381,0,0,649,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]"
];
array.forEach(function (a, i) {
lineChartData.datasets.push({
label: 'Label ' + i,
fillColor: 'rgba(220,220,220,0.2)',
strokeColor: 'rgba(220,220,220,1)',
pointColor: 'rgba(220,220,220,1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke:
'rgba(220,220,220,1)',
data: JSON.parse(a)
});
});
const ctx = document.getElementById('myChart');
new Chart(ctx, {
type: 'bar',
data: {
labels: lineChartData.labels,
datasets: lineChartData.datasets
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
Source:stackexchange.com