0

我必须创建一个基于 Json 数据的未定义列的网格,

[{
    Name: "John",
    Designation: "Analyst",
    Age: 25, 
    Department: "IT"
},
{
    Name: "Matthew",
    Designation: "Manager", 
    Age: 38, 
    Department: "Accounts"
},
{
    Name: "Emma",
    Designation: "Senior Manager",
    Age: 40,
    Department: "HR"
}];

我想要的输出如下:

作为标题:

Name | Designation | Age | Department

作为数据行:

John | Analyst | 25 | IT

请任何人帮助我如何开始以及如何做。

4

4 回答 4

0

for...in 循环将完全满足您的需求。

以下是 Mozilla 开发者网络对此的描述: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

在“for...in”循环中,测试该属性是否具有指定的属性以及该属性是否未被继承是至关重要的。(hasOwnProperty

工作示例:http: //jsbin.com/ecoqax/1/edit

我在这里使用 jQuery:

var $theader = $("thead"),
    $tbody = $("tbody"),
    hasHeader = false,
    html = "";

  // data is the converted JSON data
  for (var i = 0; i < data.length; i++) {
    // the current person
    var person = data[i];

    html += '<tr>';

    // iterating over every property of the person object
    for (var prop in person) {
      if (person.hasOwnProperty(prop)) {
        // insert the header once
        if (hasHeader === false) {
          $theader.append($('<th>'+prop+'</th>'));
        }
        html += '<td>'+person[prop]+'</td>';
      }
    }

    // after the first iteration the header is added
    hasHeader = true;
    html += '</tr>';
  }

  $tbody.append($(html));
于 2013-07-15T12:36:14.677 回答
0

Duplicate Question How to put JSON data in html / javascript grid table [if you check before posting]
this is datatables --http://datatables.net/release-datatables/examples/data_sources/js_array.html
this is gridtable JS --http://backgridjs.com/#examples

于 2013-07-15T12:16:17.120 回答
0
$.each(Jsonstring,function(){
  alert(JsonString.Name);
  alert(JsonString.Designation)
  alert(JsonString.Age)
  alert(JsonString.Department)
});
于 2013-07-15T12:23:52.733 回答
0

在这里,我已经迭代并以表格格式显示数据这就是您正在寻找的Fiddle Demo

$table = "<table id = 'resultTable' border=1>";
$.each(data[0] , function(key, value){
   $table += "<td>"+key+"</td>";
});
$table += "<tr>";

for (var i = 0; i < data.length; i++) {

    $table += "<tr>";

    var it = data[i];



    $table += "<td>" + data[i].Name + "</td>";

    $table += "<td>" + data[i].Designation + "</td>";

    $table += "<td>" + data[i].Age + "</td>";

    $table += "<td>" + data[i].Department + "</td>";

    //alert(items[i].duration);
    $table += "</tr>";

}

$table += "</table>";

$('body').append($table);
于 2013-07-15T12:29:46.087 回答