テーブルの作成
JavaScriptで表(table要素)を動的に生成します。
表示に使用するデータを変数ではなく、外部のJSONファイルとして管理し、JavaScriptから読み込むことで、データと表示ロジックを分離して利用することもできます。
データベースを使うほどではない少量のデータを扱う場合に有効で、JSONを編集するだけで表の内容を変更できるため、管理や保守が容易になります。
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./script.js"></script>
</head>
<body>
<div id="box"></div>
</body>
</html> script.js
window.onload = function() {
const datasets = {
users: {
title: "ユーザー",
config: {
headers: ['名前', '年齢'],
keys: ['name', 'age']
},
data: [
{ name: 'taro', age: 10 },
{ name: 'jiro', age: 5 },
{ name: 'hanako', age: 8 }
]
},
apple_lank: {
title: "生産量",
config: {
headers: ['順位', '都道府県名', '生産量'],
keys: ['rank', 'name', 'prod']
},
data: [
{ rank: '1', name: '青森県', prod: '370500トン' },
{ rank: '2', name: '長野県', prod: '106400トン' },
{ rank: '3', name: '岩手県', prod: '36700トン' }
]
}
};
const dataKey = 'users';
const current = datasets[dataKey];
if (!current ) return;
const { title, config, data } = current;
const table = document.createElement('table');
table.className = 'lanking';
const captionEl = document.createElement('caption');
captionEl.textContent = title;
table.appendChild(captionEl);
// thead生成
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');
config.headers.forEach(text => {
const th = document.createElement('th');
th.textContent = text;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
// tbody生成
const tbody = document.createElement('tbody');
data.forEach(item => {
const tr = document.createElement('tr');
config.keys.forEach(key => {
const td = document.createElement('td');
const value = item[key];
// 値が数値の場合はカンマ区切り、存在しない場合はハイフン
td.textContent = (typeof value === 'number')
? value.toLocaleString()
: (value ?? '-');
tr.appendChild(td);
});
tbody.appendChild(tr);
});
table.appendChild(tbody);
// DOMに追加(古いテーブルがあれば削除してから追加)
const box = document.getElementById('box');
box.innerHTML = '';
box.appendChild(table);
} JSONファイルからデータを取得する
scrip.jsの変数に直接データを書くのではなくjsonファイルに分離します。
datasets.json
{
"users": {
"title": "ユーザー",
"config": {
"headers": ["名前", "年齢"],
"keys": ["name", "age"]
},
"data": [
{ "name": "taro", "age": 10 },
{ "name": "jiro", "age": 5 },
{ "name": "hanako", "age": 8 }
]
},
"apple_lank": {
"title": "生産量",
"config": {
"headers": ["順位", "都道府県名", "生産量"],
"keys": ["rank", "name", "prod"]
},
"data": [
{ "rank": "1", "name": "青森県", "prod": "370500トン" },
{ "rank": "2", "name": "長野県", "prod": "106400トン" },
{ "rank": "3", "name": "岩手県", "prod": "36700トン" }
]
}
} script.js
window.onload = async function() {
const dataKey = 'apple_lank'; // ← ここだけ切り替え
let datasets;
try {
const response = await fetch('./datasets.json');
if (!response.ok) {
throw new Error('JSONの取得に失敗しました');
}
datasets = await response.json();
} catch (err) {
console.error(err);
return;
}
const current = datasets[dataKey];
if (!current ) return;
const { title, config, data } = current;
const table = document.createElement('table');
table.className = 'lanking';
const captionEl = document.createElement('caption');
captionEl.textContent = title;
table.appendChild(captionEl);
// thead生成
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');
config.headers.forEach(text => {
const th = document.createElement('th');
th.textContent = text;
headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);
// tbody生成
const tbody = document.createElement('tbody');
data.forEach(item => {
const tr = document.createElement('tr');
config.keys.forEach(key => {
const td = document.createElement('td');
const value = item[key];
// 値が数値の場合はカンマ区切り、存在しない場合はハイフン
td.textContent = (typeof value === 'number')
? value.toLocaleString()
: (value ?? '-');
tr.appendChild(td);
});
tbody.appendChild(tr);
});
table.appendChild(tbody);
// DOMに追加
const box = document.getElementById('box');
box.innerHTML = '';
box.appendChild(table);
}