0

次のようなjson(#json)があります。学生セクションでは、最初の2つがグループで、最後の2つがグループです(1番と2番のような番号のセットによるグループは1セットです) 。
問題は、学生セクションからデータをフェッチして2つのテーブルを作成する必要があることです(この例では2のセットの数によって異なります)。上記のことを行うためにデータをフェッチできるようにプログラムでjsonデータ構造を変更するにはどうすればよいですか?

テーブル(#table1)は次のようになります:
いいえ。名前
1トム
2ジャッキー

番号。名前
1トム
2ジャッキー


#json

{
"people": {
    "student": [{
        "name": "tom"
        "no.": "1"
        "other": "a"
    },{
        "name": "tom"
        "no.": "1"
        "other": "e"
    },{
        "name": "jack"
        "no.": "2"
        "other": "d"
    },{
        "name": "tom"
        "no.": "1"
        "other": "c"
    },{
        "name": "tom"
        "no.": "1"
        "other": "d"
    },{
        "name": "jack"
        "no.": "2"
        "other": "g"
    }]      
}}

これが私のjsRenderテンプレートです:

    <table>      
    <thead>
        <tr><td>Table 1</td></tr> 
        <tr><td>no.</td><td>name</td></tr> 
    </thead> 
    <tbody>
    {{for student}}
        <td>{{>no.}}</td>
        <td>{{>name}}</td>
    {{/for}}
    </tbody>
</table>

次のように出力されます。

no. name
1 tom
2 jacky
1 tom
2 jacky

テンプレートを変更して#table1のような出力を作成するにはどうすればよいですか?

4

1 に答える 1

0

次のようなものが必要です。

var yourJSON; // All JSON data
var studentData = yourJSON.people.student; // Student array
var tableIndex = 1; // Index for table name

// Loop to print student data
for (var i = 0, length = studentData.length; i < length; i++) {
    if (studentData[i]['no.'] == '1') {
        if (tableIndex > 1) {
            print('</tbody></table>');
        }
        print('<table>' +
            '<thead>' +
                '<tr>' +
                    '<td>Table ' + tableIndex + '</td>' +
                '</tr>' + 
                '<tr>' +
                    '<td>no.</td>' +
                    '<td>name</td>' +
                '</tr>' + 
            '</thead>' +
            '<tbody>');
        tableIndex++;
    }
    print('<tr><td>' + studentData[i]['no.'] + '</td>');
    print('<td>' + studentData[i]['name'] + '</td></tr>');
}

print('</tbody></table>'); // Closing the last table

テンプレートエンジンがどのように機能するかわからないので、印刷機能を使用して、テンプレートに追加する必要があるものを示しました。

于 2012-07-08T07:19:36.677 に答える