Reputation: 4165
I have this data:
[
[
{"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"}
]
]
How can I loop through this data in order to have two tables as shown below:
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
I have started this but got stuck:
var obj = JSON.parse(data);
$.each(obj, function(i, obj_item){
$.each(obj_item, function(j, item){
// got stuck here
})
})
Any help would be appreciated. Thanks
Upvotes: 0
Views: 121
Reputation: 36531
here u go..
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 here
Upvotes: 1
Reputation: 4912
Here you go... 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);
Let me know if it worked!
Upvotes: 1