我有一个具有对象的数组,我想在chartjs中创建折线图的数据集,但我得到的数据集是错误的,因此得到两个折线图而不是一个。我哪里做错了?
const data = [{May 04: '', May 05: '1', May 06: ''}, {May 04: '2', May 05: '', May 06: ''}]
const chartData = {
labels: ['May 04', 'May 05', 'May 06' ]
datasets: getDataSet(data),
};
const getDataSet = (data) => {
const dataSet = [];
dataSet.push({ label: 'Total' });
data.forEach((v) => {
dataSet.push({
data: Object.values(v),
});
})
return dataSet;
};
您的问题可以通过以下代码解决:
const data = [
{ 'May 04': '', 'May 05': '1', 'May 06': ''},
{ 'May 04': '2', 'May 05': '', 'May 06': ''}
];
const getDataSet = data => {
const dsData = [0, 0, 0];
data.forEach(o => Object.values(o).forEach((v, i) => dsData[i]+= Number(v)));
return {
label: 'Total',
data: dsData
};
};
const chartData = {
labels: ['May 04', 'May 05', 'May 06'],
datasets: [getDataSet(data)]
};
console.log(chartData);
如果您的数据是动态的,可以这样做:
const data = [
{ 'May 04': '', 'May 05': '1', 'May 06': '', 'May 07': '1' },
{ 'May 04': '2', 'May 05': '', 'May 06': '', 'May 07': '2' }
];
const getDataSet = data => {
const dsData = Object.keys(data[0]).fill(0);
data.forEach(o => Object.values(o).forEach((v, i) => dsData[i]+= Number(v)));
return {
label: 'Total',
data: dsData
};
};
const chartData = {
labels: Object.keys(data[0]),
datasets: [getDataSet(data)]
};
console.log(chartData);
const data = [
{ 'May 04': '', 'May 05': '1', 'May 06': '', 'May 07': '1' },
{ 'May 04': '2', 'May 05': '', 'May 06': '', 'May 07': '2' }
];
const getDataSet = data => {
const dsData = Object.keys(data[0]).fill(0);
data.forEach(o => Object.values(o).forEach((v, i) => dsData[i]+= Number(v)));
return {
label: 'Total',
data: dsData
};
};
const chartData = {
labels: Object.keys(data[0]),
datasets: [getDataSet(data)]
};
new Chart('myChart', {
type: 'line',
data: chartData,
options: {
scales: {
y: {
ticks: {
stepSize: 1
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<canvas id="myChart" height="80"></canvas>