2017-09-15 13 views
0

私は小さなプロジェクトのインターフェイスで作業しています。基本的には、APIは、次のようなJSONデータを送信します。基本的にJSONデータを定義済みの書式の表形式で表示する

{ 
"wallet_transactions": [ 
    { 
     "total_cost": "80.000", 
     "expense_type__name": "Gas", 
     "total_quantity": "5.000", 
     "trans_type": "Purchased" 
    }, 
    { 
     "total_cost": "250.000", 
     "expense_type__name": "Gas", 
     "total_quantity": "35.000", 
     "trans_type": "Rent" 
    } 
]} 

データは、そのコストとその手段(クレジット上またはそれが購入された)を与えたか、GASの多くを示しています。

私はそれから直接テーブルを構築しようとしましたが、GASが2度書き込まれて以来、非友好的な淡色でした。私が試した何

だった:

$.each(response.wallet_transactions, function(index) { 
    var exp_name=response.wallet_transactions[index].expense_type__name; 
    var quantity=response.wallet_transactions[index].total_quantity; 
    var price=response.wallet_transactions[index].total_cost; 
    var trans_type=response.wallet_transactions[index].trans_type; 

    rows=rows+'<tr><td>' + exp_name + '</td>'; 
    rows=rows + '<td>' + price + '</td>'; 
    rows=rows + '<td>' + quantity + '</td>'; 
    rows=rows + '</tr>'; 
}); 

今必要とされている出力は以下の画像のようになります。別のオブジェクトに一緒にそれぞれの名前について

enter image description here

+0

JSONは1つの名前のデータしか持たないのでしょうか、それとも、それぞれに賃貸料と購入費の両方で複数の名前を付けることができますか? – Barmar

答えて

2

グループのデータ、そして構築それからのテーブル。

var table_data = {}; 
$.each(response.wallet_transactions, function(i, trans) { 
    var exp_name = trans.expense_type__name; 
    var quantity = trans.total_quantity; 
    var price = trans.total_cost; 
    var trans_type = trans.trans_type; 
    if (!table_data[exp_name]) { 
     table_data[exp_name] = {} 
    } 
    table_data[exp_name][trans_type] = { 
     quantity: quantity, 
     cost: price 
    }; 
} 
$.each(table_data, function(name, data) { 
    rows += "<tr><td>" + name + "</td>"; 
    rows += "<td>" + data.Rent.cost + "</td>"; 
    rows += "<td>" + data.Rent.quantity + "</td>"; 
    rows += "<td>" + data.Purchased.cost + "</td>"; 
    rows += "<td>" + data.Purchased.quantity + "</td>"; 
    rows += "</tr>"; 
} 

$.eachは、コールバック関数への2番目の引数として配列要素を渡すので、あなたはすべての行にresponse.wallet_transactions[index]を繰り返す必要がないということに注意してください。

関連する問題