jQuery:JSON 对象子项处理

jQuery: JSON object children handling

本文关键字:处理 对象 JSON jQuery      更新时间:2023-09-26

我正在尝试通过javascript函数进行<table>

我得到一个看起来像这样的 JSON 元素:

header
    ["Nom", "Région", "Activité", 10 more...]
0   "Nom"   
1   "Région"
2   "Activité"
// other fields 
body
    Object { entity0=[13], entity1=[13], entity2=[13], more...}
entity0
    ["Org2", "Org2", "Org2", 10 more...]
0    "Org2"
1    "Org2" 
2    "Org2"
//Other fields
entity1
    ["gfhu", "rtyud", "dgud", 10 more...]
//Other entities

正在尝试像那样解码它(我解析 JSON 并将其提供给该函数):

function createTableEntity(tab, id){
    table = '<table cellpadding="0" cellspacing="0" border="0" class="display" id="'+id+'">';
    table = table + '<thead><tr>';
    $(tab.header).children().each(function(){
        table = table + '<td>' + this + '</td>';
    });
    table = table + '</tr></thead>';
    table = table + '<tbody>';
    $(tab.body).children().each(function(){
        table = table + '<tr>';
       $(this).children().each(function(){
           table = table + '<td>' + $(this) + '</td>';
       });
       table = table + '</tr>';
    });
    table = table + '</tbody>';
    table = table + '</table>';
    //alert(table);
    return table;
}

从我得到的结果来看,没有孩子($(tab.header).children().each(function(){});)。

它从何而来?如何遍历从 JSON 解析的元素?

你不需要jquery来循环JSON解析的结果,因为它是一个Javascript对象。

如果你在tab.header中有一个数组,你可以简单地循环它

  $.each(tab.header, function() {

或者更经典的是,没有jquery,使用

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