テーブル変換

条件

  • 値は辞書型のリスト
  • 値がaタグの場合は、リンク表示

サンプルソース

// JSONデータを表に変換する関数
function renderTable(data) {
    const table = document.createElement('table');

    // ヘッダー行を追加
    const headerRow = table.insertRow();
    for (const key in data[0]) {
        const th = document.createElement('th');
        th.textContent = key;
        headerRow.appendChild(th);
    }

    // データ行を追加
    data.forEach(item => {
        const row = table.insertRow();
        for (const key in item) {
            const cell = row.insertCell();

            // url の項目がある場合は、aタグとして処理する
            if (key === 'url') {
                const urlValue = item[key];
                // HTMLとして解釈してa要素を生成
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = urlValue.trim(); // trim() で余分な空白を除去
                const aTag = tempDiv.querySelector('a');

                if (aTag) {
                    cell.appendChild(aTag); // a要素をセルに追加
                } else {
                    cell.textContent = urlValue; // aタグが見つからない場合はそのまま表示
                }
            } else {
                cell.textContent = item[key]; // その他の項目はテキストとして表示
            }
        }
    });

    return table;
}

実装

<!DOCTYPE html>
<html lang="ja">
<head>
    <title>ランキング表示</title>
    <!-- JavaScriptファイル -->
    <script type='text/javascript' src='./js/rendertable.js'></script>
</head>

<body>
<h1 id='title'>タイトルの下にテーブルが挿入されるよ</h1>

<script>
// 出力データ(例えばAPIとかで取得したデータとか)
const jsonData = [
    { "name": "Alice", "age": 30, "city": "New York" },
    { "name": "Bob", "age": 25, "city": "Los Angeles" },
    { "name": "Charlie", "age": 35, "city": "Chicago" }
];
// 変換
const tableElement = renderTable(jsonData);
// 挿入先の要素を取得(ID指定)
var targetElement = document.getElementById('title');          
// 指定した要素の下に新しい要素を挿入
targetElement.insertAdjacentElement('afterend', tableElement);
</script>
</body>
</html>
<table>
    <thead>
        <tr>
            <th>name</th>
            <th>age</th>
            <th>city</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Alice</td>
            <td>30</td>
            <td>New York</td>
        </tr>
        <tr>
            <td>Bob</td>
            <td>25</td>
            <td>Los Angeles</td>
        </tr>
        <tr>
            <td>Charlie</td>
            <td>35</td>
            <td>Chicago</td>
        </tr>
    </tbody>
</table>
タイトルとURLをコピーしました