处理 Bootstrap 表中的嵌套数组

eas*_*999 1 json bootstrap-table

我正在处理一个 2000 多个条目的 Zotero 数据库,并希望使用Bootstrap Table公开展示它。

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

"author": [{
    "family": "Obama",
    "given": "Barack"
        }
    ,
        {
    "family": "Obama",
    "given": "Michele"
        }]
Run Code Online (Sandbox Code Playgroud)

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

更新:见jsfiddle

sni*_*ipe 5

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

表中的行标题应如下所示:

<th data-field="author" data-formatter="authorFormatter">
Run Code Online (Sandbox Code Playgroud)

在实例化引导表的 javascript 下方,您可以添加格式化程序代码。像这样的东西应该用“Barack Obama”创建一个字符串,尽管你可以随意格式化它。

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

引导程序表中的格式化程序功能使您可以轻松地保持 JSON API 干净,同时根据需要在表中显示数据。

更新

假设您的 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" ] 
            ]
    } 

}
Run Code Online (Sandbox Code Playgroud)

您的 HTML 表格将如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

你的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>
Run Code Online (Sandbox Code Playgroud)