【问题标题】:Loop through a JSON array to create a Table循环遍历 JSON 数组以创建表
【发布时间】:2014-01-29 14:29:41
【问题描述】:

我有一个 JSON 数组,我想循环创建一个表。

TITLE 等当然是表格的标题和放置在下面的相关数据。

来自 PHP 文件的 JSON 结果

[
  {
     "TITLE":"Empire Burlesque",
     "ARTIST":"Bob Dylan",
     "COUNTRY":"USA",
     "COMPANY":"Columbia",
     "PRICE":"10.90",
     "YEAR":"1985"
  },{
     "TITLE":"Picture book",
     "ARTIST":"Simply Red",
     "COUNTRY":"EU",
     "COMPANY":"Elektra",
     "PRICE":"7.20",
     "YEAR":"1985"
  }
]

PHP

$filterText = "1985";//$_REQUEST["text"];

$filename = "xml/xml_cd.xml";
$filterHeading = "YEAR";
$filterText = "1985";//$_REQUEST["text"];

$file = simplexml_load_file($filename);

$children = $file->children();
$firstchild = $children[0];
$node = $firstchild->getName();

$result = $file->xpath('//'.$node.'['. $filterHeading . '/text()="'.$filterText.'"]');

$jsondata = json_encode($result,true);

print_r($jsondata);

我认为解决方案应该使用 javascript,但由于是 JSON 和 JAVASCRIPT 的新手,我不太清楚如何解决该问题。

【问题讨论】:

    标签: javascript json loops


    【解决方案1】:

    像这样 - 使用 jQuery,因为它使 Ajax 和后续处理更加简单 - 请注意,您不必在服务器上解析 XML 并创建 JSON。您可以将 XML 提供给 jQuery 并进行类似的处理:

      // here is your success from AJAX
    
      var tbody = $("<tbody />"),tr;
      $.each(data,function(_,obj) {
          tr = $("<tr />");
          $.each(obj,function(_,text) {
            tr.append("<td>"+text+"</td>")
          });
          tr.appendTo(tbody);
      });
      tbody.appendTo("#table1"); // only DOM insertion   
    

    如果要指定每个字段:

          tr
          .append("<td>"+obj.TITLE+"</td>")
          .append("<td>"+obj.ARTIST+"</td>")      
    

    我使用的标记在哪里

    <table id="table1">
      <thead></thead>
    </table>
    

    结果:

    const data = [
      { "TITLE": "Empire Burlesque", "ARTIST": "Bob Dylan", "COUNTRY": "USA", "COMPANY": "Columbia",   "PRICE": "10.90", "YEAR": "1985" }, 
      { "TITLE": "Picture book", "ARTIST": "Simply Red", "COUNTRY": "EU", "COMPANY": "Elektra", "PRICE": "7.20", "YEAR": "1985" }];
      
    $(function() {
      const thead = $("#table1 thead");
      const tbody = $("#table1 tbody");
      let tr = $("<tr />");
    
      $.each(Object.keys(data[0]), function(_, key) {
        tr.append("<th>" + key + "</th>")
      });
      tr.appendTo(thead);
    
      $.each(data, function(_, obj) {
        tr = $("<tr />");
        $.each(obj, function(_, text) {
          tr.append("<td>" + text + "</td>")
        });
        tr.appendTo(tbody);
      });
    })
    td {
      border: 1px solid black;
      padding: 5px
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table id="table1">
      <thead>
      </thead>
      <tbody>
      </tbody>
    </table>

    【讨论】:

    • 有没有办法在不指定 .TITLE / .ARTIST 的情况下循环遍历对象?因为使用中的 JSON 文件可以随时更改。
    • 如果您有大量数据,最好进行字符串连接,而不是在每个循环上附加到 dom。您只需在 for 循环之后将一次附加到表中。
    • 如何检查 Key 是否存在?以便以后可以使用默认值替换它。例如:if (key.length == 0) {key = "-"}
    • .append("&lt;td&gt;"+(obj.TITLE || "-")+"&lt;/td&gt;")
    • @mplungjan 你会在我的例子中实现吗? jsfiddle.net/paydjo/wLg9c6j7/6
    【解决方案2】:

    你有一个对象数组,所以循环数组并定位你想要的属性:

    for (var i = 0; i < data.length; i++) {
        console.log(data[i].title);
    }
    

    要构建表格,您必须在循环内构建 HTML 并在后面追加(快速示例):

    table += "<th>" + data[i].title + "</th>";
    

    我会推荐像 MustacheJS 或 Angular 这样的模板引擎。

    【讨论】:

    • 有没有办法在不专门调用标头的情况下进行循环? (.TITLE 等)
    • 不,每次 JSON 文件更改时,您都必须重新加载。如果您想要实时更改,则需要网络套接字
    • 您可以将循环放入一个函数中,并为数组设置一个参数,并为您的属性名称设置一个参数:var myprop = 'TITLE'; for ... { ... data[i][myprop] ... },您可以在每次调用该函数时更改该参数。
    • 顺便说一下,这个解决方案是 IMO 最快的(使用字符串连接而不是多个附加到 DOM)。
    【解决方案3】:

    使用字符串连接从 JSON 构建表:

    function build(target, data, columns) {
        var head = '', rows = '';
        for (int j = 0; j < columns.length; j++) {
    
            var cols = '';
            for (int i = 0; i < data.length; i++) {
                cols += '<td>'+data[i][columns[j]]+'</td>';
            }
    
            head += '<th>'+columns[j]+'</th>';
            rows += '<tr>'+cols+'</tr>';
        }
    
        $(target).html(
            '<table>'+
                '<thead>'+head+'</thead>'+
                '<tbody>'+rows+'</tbody>'+
            '</table>'
        );
    }
    

    使用这个:

    var data = [
        {
          "TITLE":"Empire Burlesque",
          "ARTIST":"Bob Dylan",
          "COUNTRY":"USA",
          "COMPANY":"Columbia",
          "PRICE":"10.90",
          "YEAR":"1985"
       },{
          "TITLE":"Picture book",
          "ARTIST":"Simply Red",
          "COUNTRY":"EU",
          "COMPANY":"Elektra",
          "PRICE":"7.20",
          "YEAR":"1985"
       }
     ]
    
     build('#mycontainer', data, ['TITLE', 'ARTIST', 'YEAR']);
    

    会导致:

    <div id="mycontainer">
        <table>
            <thead>
                <th>TITLE</th>
                <th>ARTIST</th>
                <th>YEAR</th>
            </thead>
            <tbody>
                <tr>
                    <td>Empire Burlesque</td>
                    <td>Bob Dylan</td>
                    <td>1985</td>
                </tr>
                <tr>
                    <td>Picture book</td>
                    <td>Simply Red</td>
                    <td>1985</td>
                </tr>
            </tbody>
        </table>
    </div>
    

    【讨论】:

      【解决方案4】:

      我的解决方案是使用普通的旧 JavaScript。 为方便起见,我将一些表格元素添加到 HTML 中,而不是全部从 JS 中创建。

                  <table id="people" class='table table-striped'>
                              <thead>
                                  <th>id</th>
                                  <th>Name</th>
                                  <th>Age</th>
                                  <th>Email</th>
                                  <th>Occupation</th>
                              </thead>
                              <tbody></tbody>
                          </table>
      

      然后在我们的 JavaScript 或 JSON 文件中,我们有一些数据。我正在创建一个工厂:

      var Person = function Person(id, name,age, email, occupation) {
          this.id         = id;
          this.name       = name;
          this.age        = age;
          this.email      = email;
          this.occupation = occupation;
      };
      

      然后我将创建数据:

      var data = [
          new Person( 1,'Bill Thompson' , 45,'bill@example.com'  , 'Math Teacher' ),
          new Person( 2,'Lori Segway'   , 22,'lori@example.com'  , 'Hair Stylist' ),
          new Person( 3, 'Peggy Stiller' , 31, 'peg@example.com'  , 'Makeup Artist' ),
          new Person( 4, 'Harry Lane'    , 62, 'harry@example.com', 'Company Ceo' ),
          new Person( 5, 'Michael Lowney', 40, 'mike@example.com' , 'Gung Fu Instructor' ),
          new Person( 6,'Paul Byrant'   , 56, 'paul@example.com' , 'Web Developer' )
      ];
      

      像这样抓取 DOM 元素:

      var output = document.querySelector('#people tbody');

      并使用 forEach 循环填充表格。

      data.forEach(function (person) {
          var row = document.createElement('tr');
          ['id', 'name', 'age', 'email', 'occupation'].forEach(function (prop) {
              var td = document.createElement('td');
              td.appendChild(document.createTextNode(person[prop]));
              row.appendChild(td);
          });
          output.appendChild(row);
      });
      

      就这么简单。我使用 forEach 是因为我相信更容易看到发生了什么。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-24
        • 2021-06-08
        • 2017-04-30
        • 1970-01-01
        • 2013-02-12
        • 1970-01-01
        • 2021-09-04
        • 1970-01-01
        相关资源
        最近更新 更多