2

我刚刚开始使用 jsPDF 和 AutoTable 插件,对于我们使用它的目的来说它几乎是完美的。一个问题...

是否可以将列定义中的 dataKey 分配给正在映射到表的 JSON 中的嵌套属性?

我们有一个如下所示的 JSON 结构:

"Primary_Key": "12345",
"Site_Name": {
  "Address_Name": "Address 1"
  },
"Default_Screen_Name": "Bob",
"Full_Name": "Bob Smith"

如果我们使用以下列:

var columns = [
  { title: "ID", dataKey: "Primary_Key" },
  { title: "Screen Name", dataKey: "Default_Screen_Name" },
  { title: "Full Name", dataKey: "Full_Name" }];

一切都很完美。但是,我们还想做如下的事情:

var columns = [
  { title: "ID", dataKey: "Primary_Key" },
  { title: "Iterations", dataKey: "Iterations" },
  { title: "Screen Name", dataKey: "Default_Screen_Name" },
  { title: "Site Name", dataKey: "Site_Name.Address_Name" }];

我们Site_Name.Address_Name用于索引嵌套 JSON 对象以检索值的位置。

这样的事情可能吗?

4

1 回答 1

4

现在不行。您可以在此处遵循该功能请求。您当前的选择是在将数据传递给 autotable 之前将其展平,或者使用挂钩来提取您想要的特定文本。可以这样做:

var columns = [
    {title: "ID", dataKey: "id"},
    {title: "Name", dataKey: "name"}, 
    {title: "Country", dataKey: "address"}
];
var rows = [
    {id: 1, name: "Shaw", address: {country: "Tanzania"}},
    {id: 2, name: "Nelson", address: {country: "Kazakhstan"}},
    {id: 3, name: "Garcia", address: {country: "Madagascar"}}
];

var doc = jsPDF();
doc.autoTable(columns, rows, {
   didParseCell: function(data) {
       if (data.column.dataKey === 'address') {
           data.cell.text = data.cell.raw.country;
       }
   }
});
doc.save('table.pdf');
<script src="https://unpkg.com/jspdf@1.3.3/dist/jspdf.min.js"></script>
<script src="https://unpkg.com/jspdf-autotable@2.3.1/dist/jspdf.plugin.autotable.js"></script>

更新评论中的其他问题:

var columns = [
    {title: "Country", dataKey: "address", displayProperty: "country"},
    ...
];
var rows = [...];

...

didParseCell: function(data) {
   if (data.column.dataKey === 'address') {
       var prop = data.column.raw.displayProperty;
       data.cell.text = data.cell.raw[prop];
   }
}
于 2017-05-23T11:42:38.510 回答