这个问题已经问过了,但解决不了我的问题.
我在我的Angular 9
应用程序中实现了Chart.js
.有预期的图表价值不会到来.
我有一个API响应,因为我想使lineChartLabels
如下所述的方式stackblitz Demo.
以下是我的接口响应:
let data = [
{operatorName: 'OSEN+', date: '05-04-2023', totalCount: 1},
{operatorName: 'OSN+', date: '12-04-2023', totalCount: 7},
{operatorName: 'MBC', date: '01-06-2023', totalCount: 1},
{operatorName: 'OSEN+', date: '02-06-2023', totalCount: 1},
{operatorName: 'MBC', date: '09-06-2023', totalCount: 1},
{operatorName: 'MBC', date: '16-06-2023', totalCount: 1},
{operatorName: 'MBC', date: '23-06-2023', totalCount: 15}
];
我想用API响应设置lineChartLabels
.
预期数据集:
this.lineChartData = [
{ data: [1, 7, 0, 1, 0, 0, 0], label: 'OSEN+' },
{ data: [0, 0, 1, 0, 1, 1, 15], label: 'MBC' },
];
this.lineChartLabels = ['05-04-2023', '12-04-2023', '01-06-2023', '02-06-2023', '09-06-2023','16-06-2023', '23-06-2023' ];
这里,如果lineChartLabels
中不存在operatorName
,则将其设置为值0
.
代码:
let operators = [...new Set(data.map((x) => x.operatorName))];
let subLabelDatasets = operators.map((x) => {
let datasets = [];
for (let operator of operators) {
datasets.push(
data.find((y) => y.operatorName == operator && y.date == x)?.totalCount || 0
);
}
return {
label: x,
data: datasets,
};
});
console.log(data)
console.log(subLabelDatasets)