这个问题已经问过了,但解决不了我的问题.

我在我的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)

Expected result enter image description here

推荐答案

备注

(1)为了使我的答案更有说服力,我更改了这些变量的名称:

  • operators%至uniqueOperators%
  • x%至uniqueOperator%

(2)我把一些let改成了const,因为它从来没有重新分配过

(3)Updates

  • 在同一日期处理多个操作员
  • 添加了完整的代码

代码

您需要将您的逻辑更新为类似的内容:

const uniqueOperators = [...new Set(data.map((x) => x.operatorName))];
const uniqueDates = [...new Set(data.map((x) => x.date))];

const subLabelDatasets = uniqueOperators.map((uniqueOperator) => {
  // find by operatorName and date in `data`
  // if not found, fill with `0`
  let datasets = uniqueDates.map((uniqueDate) =>
    data.find(
      (item) =>
        item.operatorName === uniqueOperator && item.date === uniqueDate
    )?.totalCount ?? 0
  );

  return {
    label: uniqueOperator,
    data: datasets,
  };
});

这将输出一个您预期的数组:

[
    {label: 'OSEN+', data: [1, 7, 0, 1, 0, 0, 0]}
    {label: 'MBC', data: [0, 0, 1, 0, 1, 1, 15]}
]

即使API输出的数据在相同的日期包含多个运算符,该代码也会起作用:

const data = [
  { operatorName: 'OSEN+', date: '01-06-2023', totalCount: 1 },
  { operatorName: 'MBC', date: '01-06-2023', totalCount: 2 },
];

将输出:

[
    {label: 'OSEN+', data: [1]}
    {label: 'MBC', data: [2]}
]

您可以使用uniqueDates替换硬编码的lineChartLabels,如下所示

this.lineChartLabels = [...uniqueDates];

完整代码

(在您的Stackblitz演示上测试)

export class AppComponent {
  /**Line chart */
  public lineChartType: ChartType = 'line';
  public lineChartData: any = [];
  public lineChartLabels: any = [];
  public lineChartOptions = {
    responsive: true,
    scales: {
      yAxes: [
        {
          ticks: {
            beginAtZero: true,
          },
        },
      ],
    },
  };
  /**Line chart */

  ngOnInit(): void {
    let data = [
      { operatorName: 'OSEN+', date: '05-04-2023', totalCount: 1 },
      { operatorName: 'OSEN+', 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 },
    ];

    const uniqueOperators = [...new Set(data.map((x) => x.operatorName))];
    const uniqueDates = [...new Set(data.map((x) => x.date))];

    this.lineChartData = uniqueOperators.map((uniqueOperator) => {
      // find by operatorName and date in `data`
      // if not found, fill with `0`
      let datasets = uniqueDates.map((uniqueDate) =>
        data.find(
          (item) =>
            item.operatorName === uniqueOperator && item.date === uniqueDate
        )?.totalCount ?? 0
      );
    
      return {
        label: uniqueOperator,
        data: datasets,
      };
    });

    this.lineChartLabels = [...uniqueDates];
  }
}

我希望它能帮上忙!

Javascript相关问答推荐

如何在不分配整个数组的情况下修改包含数组的行为主体?

对象和数字减法会抵消浏览器js中的数字

如何分配类型脚本中具有不同/额外参数的函数类型

如何在使用fast-xml-parser构建ML时包括属性值?

使用javascript将Plotly Expandable Sparkline转换为HighCharter Plot在bslib卡中

配置WebAssembly/Emscripten本地生成问题

虚拟滚动实现使向下滚动可滚动到末尾

使用原型判断对象是否为类的实例

如何将未排序的元素追加到数组的末尾?

如何在Bootstrap中减少网格系统中单个div的宽度

是否可以将异步调用与useState(UnctionName)一起使用

postman 预请求中的hmac/sha256内标识-从js示例转换

重新呈现-react -筛选数据过多

每隔3个项目交替显示,然后每1个项目交替显示

不协调嵌入图片

JavaScript -复制到剪贴板在Windows计算机上无效

MongoDB通过数字或字符串过滤列表

在ChartJS中使用spanGaps时,是否获取空值的坐标?

P5play SecurityError:无法从';窗口';读取命名属性';Add';:阻止具有源的帧访问跨源帧

如何将值从后端传递到前端