1

我有一个 JSON 请求,它返回如下结果:

[
{"ID":"57","BookName":"Title1","AuthorID":"2" "AuthorName":"Paul"}
{"ID":"57","BookName":"Title1","AuthorID":"3" "AuthorName":"Mark"},
{"ID":"58","BookName":"Title2","AuthorID":"4" "AuthorName":"Bob"},
{"ID":"58","BookName":"Title2","AuthorID":"5" "AuthorName":"John"},
{"ID":"58","BookName":"Title2","AuthorID":"6" "AuthorName":"Chris"}
]

我想要完成的是以下 HTML 输出。为每个唯一 IDdiv创建一个具有唯一作者的新 ID。当一个新的 ID 被识别时,一个新的表格行被创建并且新的作者名字被添加到其中作为新的 div。

HTML:

<tr>
    <td>ID: 57</td>
    <td>BookName: Title1</td>
</tr>
<tr>
    <td colspan="2">
        <div class="author">
            AuthorID : 2 Author Name: Paul
        </div>
        <div class="author">
            AuthorID : 3 Author Name: Mark
        </div>
    </td>
</tr>
<tr>
    <td>ID: 58</td>
    <td>BookName: Title2</td>
</tr>
<tr>
    <td colspan="2">
        <div class="author">
            AuthorID : 4 Author Name: Bob
        </div>
        <div class="author">
            AuthorID : 5 Author Name: John
        </div>
        <div class="author">
            AuthorID : 6 Author Name: Chris
        </div>
    </td>
</tr>

这是我的 jQuery 代码,其中包含一些伪逻辑:

$.getJSON(fullurl, function(json) {
    var bookid = '';
    $.each(json, function(i,d) {
        if(d.ID!= bookid){
            make new book row
            bookid= d.ID
         }
        else 
            use same row to show author div
         }
     }//end foreach

有人可以帮我理解我该怎么做吗?

4

1 回答 1

2

如果您无法在可以使用的结构中获得 JSON 输出,则必须对其进行操作。您想按书籍对作者进行分组。

var books = {};
$.each(json, function () {
    if (!books.hasOwnProperty(this.ID)) {
        books[this.ID] = {
            "ID": this.ID,
            "BookName": this.BookName,
            "authors": []
        };
    }
    books[this.ID].authors.push({"AuthorID": this.AuthorID, "AuthorName":
        this.AuthorName});
});

它应该相对容易循环books,它具有所需的结构,并按照您在上面解释的那样附加表行。

http://jsfiddle.net/rAYFZ/

于 2013-03-27T14:43:00.947 回答