我刚开始使用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对象以检索值。
这样的事情可能吗?
答案 0 :(得分:4)
目前不是。您可以关注该功能请求here。您的选项目前要么是在将数据传递给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, {
createdCell: function(cell, data) {
if (data.column.dataKey === 'address') {
cell.text = 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>
&#13;
更新以获取评论中的其他问题(需要v2.3.2):
var columns = [
{title: "Country", dataKey: "address", displayProperty: "country"},
...
];
var rows = [...];
...
createdCell: function(cell, data) {
if (data.column.dataKey === 'address') {
var prop = data.column.raw.displayProperty;
cell.text = cell.raw[prop];
}
}