2014-12-10 59 views
1

我一直在試圖構建過去幾天的動態表格。我已經建立了幾種不同的方式,並最終將其轉化爲具有正確輸出的點,但是我所做的工作都是手動的。我希望有人能幫助我做到這一點。從JSON構建動態表格

這裏的(超級簡單)

var obj1 = { 
"Summary" : 
[ 
{ 
    "ID" : "1234", 
    "Name" : "John", 
    "Status" : "Green", 
}, 
{ 
    "ID" : "5678", 
    "Name" : "Mike", 
    "Status" : "Green", 
}, 
{ 
    "ID" : "9012", 
    "Name" : "Tom", 
    "Status" : "Red", 
}, 
{ 
    "ID" : "3456", 
    "Name" : "Chris", 
    "Status" : "Red", 
}, 
{ 
    "ID" : "2445", 
    "Name" : "Pat", 
    "Status" : "Green", 
}, 
{ 
    "ID" : "6543", 
    "Name" : "James", 
    "Status" : "Red", 
} 

] 
}; 

我需要的輸出是這個樣子(這是),但我可以在我的數組有超過6個對象,所以我在我的JSON的例子需要遍歷這個而不是手動構建它。

1234 5678 9012 3456 2445 6543 
John Mike  Tom Chris Pat  James 
Green Green Red  Red  Green Green 

這是我的代碼到目前爲止。任何幫助將非常感激。

for (j in obj1.Summary[0]) { 
document.write('<tr><td class="' + j +'">' + j + '</td><td class="' + j +'">' +  obj1.Summary[0][j] + '</td><td class="' + j +'">' + obj1.Summary[1][j] + '</td><td class="' + j +'">' + obj1.Summary[2][j] + '</td><td class="' + j +'">' + obj1.Summary[3][j] + '</td><td class="' + j +'">' + obj1.Summary[4][j] + '</td><td class="' + j +'">' + obj1.Summary[5][j] + '</td></tr>'); 
} 
+0

嵌套循環如何? – 2014-12-10 21:52:15

回答

1

做一個變量並把文本放在那裏。這樣你就可以使用嵌套循環來構建它,然後將它插入到文檔中。我只是在PHP中做了類似的事情,可以將數據庫表作爲嵌套數組並從中生成一個表。

var table = "<table>"; 

//we loop over the attributes since you want that format 
for (userAttribute in obj1.Summary[0]) { 
    //these are your headers/titles 
    table += '<tr><th>' + userAttribute + '</th>'; 

    //and here we build a row getting the attribute from each user 
    for (userIndex in obj1.Summary) { 
    var user = obj1.Summary[userIndex]; 
    table += '<td>' + user[userAttribute] + '</td>'; 
    } 
    table += '</tr>'; //close that row and move on to the next attribute 
} 

//close out the table 
table += '</table>'; 

document.write(table); 
1

當你想重複邏輯,你應該使用循環。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

for (var i=0; i < obj.Summary.length; i++) { 
    var object = obj.Summary[i] 
    // write to document 
} 

您應該調換數據或更改接口。

1234 John Green 
5678 Mike Green 

您可能會發現一個渲染庫也很有用,以避免與字符串連接混淆。

https://github.com/leonidas/transparency

編輯

沒問題,還是使用循環。在循環中構建行並將它們連接在一起。請參閱mdn array docs,特別是forEachjoin

// specify keys and init rows 

var keys = [ "ID" ] 
var rows = {} 

keys.forEach(function (key) { 
    rows[key] = [] 
}) 

// ok now we have rows 

console.log(rows) 

// add table cells to rows 

summaryObjects.forEach(function (object) { 
    for (var key in object) { 
    var cell = "<td>" + object[key] + "</td>" 
    rows[key].push(cell) 
    } 
}) 

// now we have cells in the rows 

console.log(rows) 

// put together the table 

keys.forEach(function (key) { 
    document.write("<tr>" + rows[key].join('') + "</tr>") 
}) 

這就是我的意思上面,像一個矩陣線性代數調換。你的數據是這樣的:

[ 
    { key: value, key: value } 
    { key: value, key: value } 
] 

而你要

{ 
    key: [ value, value ], 
    key: [ value, value ] 
} 
+0

AJcodez我嘗試過,但是因爲你遇到了它不符合我想要的格式。它的產量從西到東,但我需要從北到南。 – user2828701 2014-12-10 22:02:06

+0

@ user2828701是否更有意義? – AJcodez 2014-12-10 22:15:32

+0

AJcodez afk現在。將很快檢查。感謝迄今的援助 – user2828701 2014-12-11 00:26:05

0

我會使用模板,如Handlebarsjs做到這一點建議。通過這種方式,您可以將html與JavaScript分開,而且不必添加太多'+'。

例如,您可以將其嵌入到您的html中。

<script id="template" type="text/x-handlebars-template"> 

    {{#each Summary}} 

     <tr><td>{{this.ID}}</td> 
      <td>{{this.Name}}</td> 
      <td>{{this.Status}}</td> 
     </tr> 

    {{/each}} 
</script> 

我想我搞砸了標籤,但你明白了。

然後在腳本文件中,您可以編譯模板並獲取數據。有關http://handlebarsjs.com/的更多信息

var PROJECT_METHOD ={ 

      handlerData:function(resJSON){ 

       var templateSource = $("#template").html(), 

        template = Handlebars.compile(templateSource), 

        projectHTML = template(resJSON), 

        parser = new DOMParser(), 

        // the result 
        doc = parser.parseFromString(projectHTML, "text/html"); 
        document.write(doc); 

      }, 
      loadProjectData : function(){ 

       $.ajax({ 
        url:"data.json", 
        method:'get', 
        success:this.handlerData 
       }); 
      } 
     }; 

     PROJECT_METHOD.loadProjectData(); 

希望它有幫助。

2

我最近想出了創建通過動態數據庫產出表的一個有趣的模式,同時舉行的有關創建的元素和引用用於創建它們的值。

這個方法對我來說非常方便,因爲我爲每個表格單元格創建了輸入元素,然後使用創建的結構來檢查原始值與他們的實際值並根據更改的字段生成sql更新查詢。

我意識到這可能是矯枉過正的這種具體情況,但它確實有助於可讀性和可維護性,所以我在這裏發佈它以防萬一它可能在未來幫助其他人。

var responseText = {"Summary":[{"ID":"1234","Name":"John","Status":"Green",}, {"ID":"5678","Name":"Mike","Status":"Green",}, {"ID":"9012","Name":"Tom","Status":"Red",}, {"ID":"3456","Name":"Chris","Status":"Red",}, {"ID":"2445","Name":"Pat","Status":"Green",}, {"ID":"6543","Name":"James","Status":"Red",}]}; 
 

 
var list = new List(responseText.Summary); 
 
document.body.appendChild(list.node); 
 

 
function List(data) { 
 
    if(!(this instanceof List)) return false; 
 
    var list = this.node = document.createElement('div'); 
 
    list.setAttribute('class','list'); 
 
    var items = this.items = {}; 
 
    for(var i in data) { 
 
     items[i] = new ListItem(data[i]) 
 
     list.appendChild(items[i].node); 
 
    } 
 
} 
 
function ListItem(data) { 
 
    if(!(this instanceof ListItem)) return false; 
 
    var item = this.node = document.createElement('div'); 
 
    item.setAttribute('class','item'); 
 
    var lines = this.lines = {}; 
 
    for(var i in data) { 
 
     lines[i] = new ListItemLine(i, data[i]) 
 
     item.appendChild(lines[i].node); 
 
    } 
 
} 
 
function ListItemLine(name, value) { 
 
    if(!(this instanceof ListItemLine)) return false; 
 
    var line = this.node = document.createElement('div'); 
 
    this.name = name; 
 
    this.value = value; 
 
    line.setAttribute('class','line ' + name); 
 
    if(name !== 'ID') 
 
     line.setAttribute('contenteditable', true); 
 
    line.appendChild(document.createTextNode(value)); 
 
}
.item { 
 
    display: inline-block; 
 
    padding: 5px; 
 
    text-align: center; 
 
}

然後我用類似這樣的List類裏面的東西,

list.onkeydown = function(e) { 
    if(e.which !== 13) return true; 
    e.preventDefault(); 
    var changes = []; 
    for(var i in items) (function(item, data){ 
     for(var i in data.lines) (function(line){ 
      var value = line.value, 
       actual = line.node.textContent; 
      if(value !== actual) changes.push({ 
       id: data.lines['ID'].value, 
       name: line.name, 
       value: actual 
      }); 
     })(data.lines[i]); 
    })(i, items[i]); 
    console.log(encodeURIComponent(JSON.stringify(changes))); 
} 

它不使用的console.log,我通過AJAX將數據發送到接收器頁面生成更新sql並返回查詢結果。當然,做這個最後一部分的方法有很多,這對我來說是最有用的。