访问jspdf autotable插件中的嵌套JSON属性 [英] Access nested JSON property in jspdf autotable plugin

查看:87
本文介绍了访问jspdf autotable插件中的嵌套JSON属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have just started using jsPDF and the AutoTable plugin, and it is almost perfect for what we are using it for. One question...

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

Is it possible to assign a dataKey in the columns definition to a nested property within the JSON that is being mapped to the table?

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

We have a JSON structure that looks like this:

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

一切正常.但是,我们还要执行以下操作:

Everything works perfectly. However, we would also like to do something like the following:

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对象以检索值.

Where we are using Site_Name.Address_Name to index into the nested JSON object to retrieve the value.

这样可能吗?

推荐答案

暂时没有.您可以在此处遵循该功能请求.当前您的选择是在将数据传递到自动表之前将其展平,或使用挂钩提取所需的特定文本.可以这样完成:

Not at the moment. You can follow that feature request here. Your options are currently to either flatten the data before passing it to autotable or use the hooks to extract the specific text you want. That can be done like this:

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>

更新以获取评论中的其他问题

Update for additional question in comments:

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

这篇关于访问jspdf autotable插件中的嵌套JSON属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆