处理 Bootstrap Table 中的嵌套数组

Processing nested arrays in Bootstrap Table

我正在处理一个包含 2000 多个条目的 Zotero 数据库,并希望使用 Bootstrap Table.

公开展示它

但是,由于 Zotero 字段的工作方式,即作者字段,我对 JSON 文件有疑问。示例:

"author": [{
    "family": "Obama",
    "given": "Barack"
        }
    ,
        {
    "family": "Obama",
    "given": "Michele"
        }]

如果我使用 "author" 字段,这将转换为 [Object Object],或者我可以使用 FlatJson 扩展并仅使用 嵌套值(通过 "author.0.family"),这会中断搜索并且不会 return all 作者。

更新:见jsfiddle

您应该能够使用行格式化程序来处理它。

您的 table 中的行 header 应如下所示:

<th data-field="author" data-formatter="authorFormatter">

在实例化您的 bootstrap table 的 javascript 下方,您可以添加格式化程序代码。像这样的东西应该用 "Barack Obama" 制作一个字符串,尽管你可以按照你喜欢的方式格式化它。

<script>
function authorFormatter(value, row) {
    if ((value) && (value[0].given)) {
        return value[0].given + ' ' + value[0].family;
    }
}
</script>

bootstraptables 中的格式化程序功能使您可以轻松地保持 JSONAPI 干净,同时根据需要在 table 中显示数据.

更新

假设您的 JSON 看起来像这样(基于您的示例):

{ 
"type": "chapter", 
"title": "Long title", 
"container-title": "Other title", 
"publisher": "Publisher", 
"publisher-place": "City", 
"page": "XX-XX", 
"source": "Library", 
"ISBN": "XXXXXXXXXXX", 
"container-author": 
    [ 
        { 
            "family": "XXX", 
            "given": "XXX" 
        } 
    ], 
    "author": 
    [
        { 
            "family": "Obama", 
            "given": "Barack" 
        }, 
        { 
            "family": "Obama", 
            "given": "Michelle" 
        } 
    ],
    "issued": 
    { 
        "date-parts": 
            [ 
                [ "2012" ] 
            ]
    } 

}

您的 HTML table 看起来像这样:

<table 
id="table"
class="table table-striped"
data-toggle="table"
data-url="https://url.to.your.json"
data-side-pagination="server">
    <thead>
        <tr>
            <th data-field="author" data-formatter="authorsFormatter">Authors</th>
        </tr>
    </thead>
</table>

你的 javascript 看起来像这样:

<script>
// Initialize the bootstrap-table javascript
var $table = $('#table');
$(function () {
});

// Handle your authors formatter, looping through the 
// authors list
function authorsFormatter(value) {
    var authors = '';

    // Loop through the authors object
    for (var index = 0; index < value.length; index++) {
        authors += value[index].given + ' ' + value[index].family;

        // Only show a comma if it's not the last one in the loop
        if (index < (value.length - 1)) {
            authors += ', ';
        }
    }
    return authors;
}
</script>