在 jspdf autotable 插件中访问嵌套 JSON 属性

Access nested JSON property in jspdf autotable plugin

我刚刚开始使用 jsPDF 和 AutoTable 插件,它几乎完美地满足了我们的使用需求。一个问题...

是否可以将列定义中的 dataKey 分配给映射到 table 的 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 对象以检索值。

这样的事情可能吗?

暂时没有。您可以关注该功能请求 here。您目前的选择是要么在将数据传递给自动表之前展平数据,要么使用挂钩提取您想要的特定文本。可以这样做:

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];
   }
}