我有这些数据:
[
[
{"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
})
})
任何帮助将不胜感激。感谢
答案 0 :(得分: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);
让我知道它是否有效!
答案 1 :(得分: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
fiddle此处