我有一个这种格式的JavaScript对象:
{
"info": {
"": {
"apple": "8",
"orange": "4"
},
"Jason Family": {
"a": {
"apple": "2",
"orange": "2"
},
"b": {
"apple": "2"
}
},
"Alex Family": {
"a": {
"apple": "2",
"orange": "2"
},
"b": {
"apple": "2"
}
}
}
}
现在我想在Javascript中解析并以表格格式显示它。我的预期输出如下
Jason Family Alex family
Apple(8) | a(2) |b(2) | a(2) |b(2) |
Orange(4) | a(2) | a(2) |
我认为最好的方法是阅读对象并使用我需要的结构创建一个新对象。我试过这个:
var str = [];
str.push('<table border="0" cellpadding="1" cellspacing="1" class="om" id="tbl_data" name="tbl_data" >');
str.push('<thead>');
str.push('<tr>');
str.push('<th colspan="2" style="vertical-align:middle;">Info</th>');
str.push('</tr>');
str.push('<tr>');
if(data_rtn["info"] != ""){
str.push('<td colspan="2">');
for(data in data_rtn){
if(data == "info"){
for(midx in data_rtn[data]){
str.push('<table border="0" cellpadding="1" cellspacing="1" class="om" style="float:left">');
str.push('<tr>');
if(midx == ""){
str.push('<td colspan="2" style="background:yellow"> </td>');
}else{
str.push('<td colspan="2" style="background:yellow">'+midx+'</td>');
}
str.push('</tr>');
for(type in data_rtn[data][midx]){
for (total in data_rtn[data][midx][type]){
if(type == "error"){
str.push('<tr>');
str.push('<td colspan="2">'+data_rtn[data][midx][type]+'</td>');
str.push('</tr>');
}else{
str.push('<tr>');
str.push('<td style="text-align:left;">'+type+'('+data_rtn[data][midx][type][total]+')</td>');
str.push('</tr>');
}
}
}
str.push('</table>');
}
}
}
str.push('</td>');
}else{
alert("no record!");
}
str.push('<tr><td colspan="2"><a href="javascript:void(0)" onclick="closeDiv();">Close</a></td></tr>');
str.push('</table>');
return_data = str.join("");
$('#pop_list').css({'top':tmpPosy,'left':posx+10,'position':'absolute','text-align':'center'});
$('#pop_list').html(return_data);
$('#pop_list').show();
上面的代码输出如下
输出:
Jason Family Alex family
Apple(8) | a(2) | a(2) |
Orange(4) | a(2) | a(2) |
| b(2) | b(2)
但上面的代码并没有像我预期的那样产生输出。有人可以指出我正确的方向吗?谢谢!
答案 0 :(得分:0)
我建议使用Angular。将值放在表中。请参阅下面的代码,以获得一个粗略的想法。它可以为您节省大量代码空间并使其更快。
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function (response) {$scope.names = response.records;});
});
</script>