LoginSignup
3
6

More than 5 years have passed since last update.

JavaScriptでオブジェクトの配列からTableを作る

Last updated at Posted at 2017-12-12

要件

  • シンプルなオブジェクトの配列からさくっと表を作る
    • ネストしたオブジェクトは考慮しない
[
  {
    "THUMBNAIL":"https://www.google.co.jp/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png",
    "NAME":"Google",
    "URL":"https://www.google.co.jp/"},
  {
    "THUMBNAIL":"https://s.yimg.jp/images/top/sp2/cmn/logo-170307.png",
    "NAME":"Yahoo",
    "URL":"https://www.yahoo.co.jp/"},
];
  • 列名はオブジェクトのキー
  • 既存のtableタグの中身を更新する(対象のtableのid名を引数として渡す)

期待する表

THUMBNAIL NAME URL
代替テキスト Google https://www.google.co.jp/
代替テキスト Yahoo https://www.yahoo.co.jp/

コード

class TableMaker{
  // jsonはオブジェクトの配列
  static make({tableId = null, json = null, headers = []} = {}){
    const table = document.getElementById(tableId);
    if(typeof json === 'string') json = JSON.parse(json);
    table.innerHTML = this.build(json, headers);
  }

  static build(json, headers){
    const rows = json.map(row => {
      if(headers.length === 0) headers = Object.keys(row);
      const tdsStr = headers.map(h => {
        let v = row[h];
        if(h === 'THUMBNAIL') v = `<img src="${v}">`;
        return `<td class="${h}">${v}</td>`;
      }).join('')
      return `<tr>${tdsStr}</tr>`;
    });
    const thsStr = headers.map(h => `<th class="${h}">${h}</th>`).join('');
    const rowsStr = rows.join('');
    return `<thead><tr>${thsStr}</tr></thead><tbody>${rowsStr}</tbody>`;
  }
}

TableMaker.make({tableId: 'resultTable', json: data});

サンプル

ローカルに適当にHTMLファイルを作ってコピペして開いてみてください。

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>Table Maker</title>
  <style>
table, td, th {
  border-collapse: collapse;
  border:1px solid #333;
}
td{
  padding: 5px;
}
td.THUMBNAIL img{
  width: 100px;
}
  </style>
</head>
<body>
<table id="resultTable"></table>
<script>
class TableMaker{
  // jsonはオブジェクトの配列
  static make({tableId = null, json = null, headers = []} = {}){
    const table = document.getElementById(tableId);
    if(typeof json === 'string') json = JSON.parse(json);
    table.innerHTML = this.build(json, headers);
  }

  static build(json, headers){
    const rows = json.map(row => {
      if(headers.length === 0) headers = Object.keys(row);
      const tdsStr = headers.map(h => {
        let v = row[h];
        if(h === 'THUMBNAIL') v = `<img src="${v}">`;
        return `<td class="${h}">${v}</td>`;
      }).join('')
      return `<tr>${tdsStr}</tr>`;
    });
    const thsStr = headers.map(h => `<th class="${h}">${h}</th>`).join('');
    const rowsStr = rows.join('');
    return `<thead><tr>${thsStr}</tr></thead><tbody>${rowsStr}</tbody>`;
  }
}

const data = [
  {
    "THUMBNAIL":"https://www.google.co.jp/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png",
    "NAME":"Google",
    "URL":"https://www.google.co.jp/"},
  {
    "THUMBNAIL":"https://s.yimg.jp/images/top/sp2/cmn/logo-170307.png",
    "NAME":"Yahoo",
    "URL":"https://www.yahoo.co.jp/"},
];

TableMaker.make({tableId: 'resultTable', json: data});
// headersにカラム名の配列を渡すとその順番で表を作成
// TableMaker.make({tableId: 'resultTable', json: data, headers: ['URL', 'NAME']});
</script>
</body>
</html>
3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6