Angular 带有嵌套 JSON 的 PDFMake 动态 Table

Angular PDFMake Dynamic Table with Nested JSON

我使用了在这里 Building table dynamically with PDFMake 找到的代码,它可以很好地处理来自 API 的动态数据。但我的问题是嵌套 JSON.

这是 JSON 的样子:

dataseries":[
      {
         "timepoint":3,
         "cloudcover":2,
         "seeing":6,
         "transparency":2,
         "lifted_index":10,
         "rh2m":2,
         "wind10m":{
            "direction":"N",
            "speed":2
         },
         "temp2m":23,
         "prec_type":"none"
      },
      {
         "timepoint":6,
         "cloudcover":2,
         "seeing":6,
         "transparency":2,
         "lifted_index":15,
         "rh2m":3,
         "wind10m":{
            "direction":"N",
            "speed":2
         },
         "temp2m":21,
         "prec_type":"none"
      },

我正在尝试生成 wind10m 的内容,特别是 directionspeed PDF 文件。如何访问和生成两个不同的列 directionspeed?

这是我的 stackblitz 演示:https://stackblitz.com/edit/angular-ojgxtj?file=src%2Fapp%2Fapp.component.ts

你应该使用 JSON.stringify 而不是 .toString()

JSON.stringify() method converts a JavaScript value to a JSON string,

如果指定了替换函数,可选择替换值,或者如果指定替换数组,可选择仅包含指定的属性。

发件人:

dataRow.push(row[column].toString());

dataRow.push(JSON.stringify(row[column]));

嵌套 wind10m 列的更新:

您需要将 colSpan 和 rowSpan 属性添加到 table 行。

Stackblitz

  buildTableBody(data, columns, c2) {
    var body = [];

    //push first and second row
    body.push(columns);
    body.push(c2);
    data.forEach(function (row) {
      var dataRow = [];
      columns.forEach(function (column) {
        if (column.text == 'timepoint' || column.text == 'cloudcover') {
          dataRow.push(JSON.stringify(row[column.text]));
        } else if (column.text == 'wind10m') {
          dataRow.push(row['wind10m']['direction']);
        } else {
          dataRow.push(row['wind10m']['speed']);
        }
      });
      body.push(dataRow);
    });

    return body;
  }

  generatePdf() {
    console.log('generatePdf');

    let docDefinition = {
      content: [
        { text: 'PDF Generate', style: 'header' },
        this.table(
          this.holder,
          //first row
          [
            { text: 'timepoint', rowSpan: 2 },
            { text: 'cloudcover', rowSpan: 2 },
            { text: 'wind10m', colSpan: 2 },
            '',
          ],
          //second row
          [
            '',
            '',
            { text: 'direction' },
            { text: 'Speed' },
          ]
        ),
      ],
    };
    pdfmake.createPdf(docDefinition).open();
  }