0

我有这个数据:

[
   [
      {"id":"1", "sentiment":"0", "name":"Company 1", "count":"10"},
      {"id":"2", "sentiment":"0", "name":"Company 2", "count":"5"},
      {"id":"3", "sentiment":"0", "name":"Company 3", "count":"7"}   
   ],
   [
      {"id":"1", "sentiment":"1", "name":"Company 1", "count":"3"},
      {"id":"2", "sentiment":"1", "name":"Company 2", "count":"2"},
      {"id":"3", "sentiment":"1", "name":"Company 3", "count":"4"}   
   ]
]

我如何遍历这些数据以获得两个表,如下所示:

id     Company     sentiment      count
1      Company 1        0           10
2      Company 2        0            5
3      Company 3        0            7

id     Company     sentiment      count
1      Company 1        1           3
2      Company 2        1           2
3      Company 3        1           4

我已经开始了,但卡住了:

var obj = JSON.parse(data);
  $.each(obj, function(i, obj_item){
     $.each(obj_item, function(j, item){
    // got stuck here                   
     })
})

任何帮助,将不胜感激。谢谢

4

2 回答 2

1

给你... http://jsfiddle.net/kbVg4/

var table = '';
for(var i = 0; i < data.length; i++){
    //One table per subset
    table += '<table>';

    //Table headers
    table += '<tr><th>Id</th><th>Company</th><th>Sentiment</th><th>Count</th></tr>';

    //Looping over the subset
    for(var j = 0; j < data[i].length; j++){
        table += '<tr>';
        table += '<td>'+data[i][j]['id']+'</td>';
        table += '<td>'+data[i][j]['name']+'</td>';
        table += '<td>'+data[i][j]['sentiment']+'</td>';
        table += '<td>'+data[i][j]['count']+'</td>';
        table += '</tr>';
    }
    table += '</table>';
}

//Use the appropriate ID.
$('body').append(table);

让我知道它是否有效!

于 2013-01-04T13:24:49.107 回答
1

给你..

var data= "your show json array in question";

var str="";
 $.each(data, function(i, obj_item){
    str+="<table border='1'>";
     str+="<tr><td>id</td><td>sentiment</td><td>name</td><td>count</td>";
    $.each(obj_item, function(i1, obj){

        str+="<tr><td>"+obj.id+"</td><td>"+obj.sentiment+"</td><td>"+obj.name+"</td><td>"+obj.count+"</td>";
       str+="</tr>";
    });
     str+="</table>";

});

 $('div').html(str);//replace with your selector

在这里摆弄

于 2013-01-04T13:28:43.043 回答