Skip to content

Instantly share code, notes, and snippets.

@twlca
Last active June 16, 2016 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twlca/6c5ff1ce083506ca3203d71a13602e85 to your computer and use it in GitHub Desktop.
Save twlca/6c5ff1ce083506ca3203d71a13602e85 to your computer and use it in GitHub Desktop.
示範由 JSON data 轉換成 HTML table 資料表
var members = "[{"name":"林慶福","birthday":{"year":1969,"month":10,"day":10},"pid":"V120405500","qualification":"實習志工","ID":1},{"name":"陳美玲","birthday":{"year":1961,"month":3,"day":31},"pid":"V220499424","qualification":"實習志工","ID":2},{"name":"鄭淑雲","birthday":{"year":1971,"month":11,"day":2},"pid":"V220333387","qualification":"實習志工","ID":3},{"name":"廖心如","birthday":{"year":1959,"month":6,"day":11},"pid":"V220410209","qualification":"實習志工","ID":4},{"name":"蔡馥伊","birthday":{"year":1971,"month":5,"day":26},"pid":"V220605306","qualification":"實習志工","ID":5},{"name":"李金發","birthday":{"year":1965,"month":3,"day":7},"pid":"V120045031","qualification":"社字第054333號","ID":6},{"name":"邱淑娟","birhtday":{"year":1965,"month":3,"day":7},"pid":"V120045031","qualification":"實習志工","ID":7},{"name":"楊菊花","birthday":{"year":1961,"month":10,"day":28},"pid":"V220096174","qualification":"實習志工","ID":8}]"
function table_title( object ) {
var html = '';
if ( object && keys(object[0])) {
html += '<table><tr>';
for (var i=0; i<keys(object[0]).length; i++) {
html += '<th>' + keys(object[0])[i] + '</th>';
}
html += '</tr>';
}
for (var j=0; j<object.length; j++) {
html += '<tr>';
for (var k in values(object[j])) {
if ( typeof values(object[i])[k] == 'object' ) {
var fulldate = values(values(object[j])[k]).join('.');
html += '<td>' + fulldate + '</td>';
} else {
html += '<td>' + values(members[j])[k] + '</td>';
}
}
html += '</tr>';
}
html += '</table>';
return html;
}
@twlca
Copy link
Author

twlca commented Jun 16, 2016

json2table.js

json2table.js 是一段簡短的 JavaScript 程式,它將深度兩層的 JSON 資料表轉換成 HTML 表格。層次二是以生日為範例,將出生年、月、日以 '.' 合併

可以改進的空間

  1. 資料表欄位可選擇
  2. 資料表欄位順序可調整
  3. 資料表可排序
  4. 生日可轉換成西曆格式或民國年格式
  5. 資料表標題可自定

使用 json2table.js

  1. 先將 JSON 資料轉換成 JSON Object

    member_obj = JSON.parse( members );

  2. member_obj 作為 json2table 的引數 object 代入函數中

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment