I have used a code I found on here Building table dynamically with PDFMake it works perfectly fine with dynamic data coming from an API. But my problem is Nested JSON.
This is how the JSON looks like:
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"
},
I am trying to generate the content of wind10m specifically the direction and speed on the PDF file. How do I access and generate two different columns of direction and speed?
This is my stackblitz demo:https://stackblitz.com/edit/angular-ojgxtj?file=src/app/app.component.ts
CodePudding user response:
You should use JSON.stringify instead of .toString()
JSON.stringify() method converts a JavaScript value to a JSON string,
optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
From:
dataRow.push(row[column].toString());
to
dataRow.push(JSON.stringify(row[column]));
Update for nested wind10m column:
You need to add the colSpan and rowSpan properties to the table rows.
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();
}