では、先ほどの 動的ネスト配列の整形サンプル を、ブラウザでそのまま HTMLテーブルとして表示するサンプル にします。
🌐 HTMLで表示するサンプル
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>注文一覧表示サンプル</title>
<style>
table {
border-collapse: collapse;
width: 80%;
margin: 20px auto;
}
th, td {
border: 1px solid #aaa;
padding: 8px;
text-align: left;
}
th {
background-color: #eee;
}
.high {
background-color: #ffdede;
}
.normal {
background-color: #deffde;
}
</style>
</head>
<body>
<h2 style="text-align:center;">注文一覧</h2>
<table id="orderTable">
<thead>
<tr>
<th>注文ID</th>
<th>顧客名</th>
<th>商品詳細</th>
<th>合計金額(税込)</th>
<th>ラベル</th>
</tr>
</thead>
<tbody>
<!-- ここに JS で行を追加 -->
</tbody>
</table>
<script>
let orders = [
{
id: 1,
customer: { firstName: 'Sora', lastName: 'Yamada' },
items: [
{ name: 'Pen', price: 100, quantity: 2 },
{ name: 'Notebook', price: 250, quantity: 1 }
]
},
{
id: 2,
customer: { firstName: 'Mina', lastName: 'Kato' },
items: [
{ name: 'Bag', price: 1200, quantity: 1 },
{ name: 'Pencil', price: 50, quantity: 3 },
{ name: 'Eraser', price: 80, quantity: 2 }
]
},
{
id: 3,
customer: { firstName: 'Taro', lastName: 'Suzuki' },
items: [] // 商品が0件
}
];
// mapでUI用に整形
let displayOrders = orders.map(order => ({
orderId: order.id,
customerName: `${order.customer.firstName} ${order.customer.lastName}`,
items: order.items.map(item => ({
name: item.name,
quantity: item.quantity,
priceWithTax: Math.round(item.price * 1.1)
})),
totalAmount: order.items
.map(item => item.price * item.quantity * 1.1)
.reduce((sum, amount) => sum + amount, 0)
})).map(order => ({
...order,
label: order.totalAmount > 1000 ? '高額' : '普通'
}));
// HTMLテーブルに表示
let tbody = document.querySelector("#orderTable tbody");
displayOrders.forEach(order => {
let tr = document.createElement("tr");
tr.className = order.label === '高額' ? 'high' : 'normal';
let itemsText = order.items.length > 0 ?
order.items.map(item => `${item.name} x${item.quantity} (${item.priceWithTax}円)`).join("<br>") :
'商品なし';
tr.innerHTML = `
<td>${order.orderId}</td>
<td>${order.customerName}</td>
<td>${itemsText}</td>
<td>${order.totalAmount}円</td>
<td>${order.label}</td>
`;
tbody.appendChild(tr);
});
</script>
</body>
</html>
HTML✅ ポイント解説
- JSのmapで整形した配列をそのまま使える
displayOrdersに UI 用データが揃っているので、ループで<tr>を作るだけ
- 条件で色分け
- ラベルが
"高額"の場合は背景色赤系、"普通"は緑系
- ラベルが
- ネスト配列も
<br>で表示- 商品が複数でも見やすく整形
- 商品0件でも対応
items.length > 0 ? ... : '商品なし'で表示を工夫
💡 このサンプルをブラウザで開くと、リアルな注文一覧テーブル として表示されます。
- 商品数が増減しても自動で行が作られる
- 税込計算やラベル付けも map 内で一括処理
