如何基于对象数组绘制行列去重的动态HTML表格?
问题描述
我有如下结构的对象数组:
const reports = [ { user: "John", document: [ { document_name: "word", document_type: 1, cid: 2, }, { document_name: "excel", document_type: 1, cid: 2, }, ], }, { user: "Matt", document: [ { document_name: "access", document_type: 1, cid: 1, }, { document_name: "word", document_type: 1, cid: 3, }, ], }, ];
需要生成一个HTML表格,要求:
- 列为去重后的用户
- 行为去重后的document_name
- 单元格填充对应的
cid值,无对应值则留空
目标表格效果如下:
| John | Matt | |
|---|---|---|
| word | 2 | 3 |
| excel | 2 | |
| access | 1 |
注:修正原示例中Matt对应word的cid笔误,实际应为3。
解决方案
1. 数据预处理
首先从原始数组中提取关键数据并建立映射,方便后续表格生成:
// 提取去重后的用户列表 const users = [...new Set(reports.map(item => item.user))]; // 提取去重后的文档名列表 const documentNames = [...new Set(reports.flatMap(item => item.document.map(doc => doc.document_name)))]; // 建立「用户-文档名」到cid的映射表 const cidMap = {}; reports.forEach(userItem => { cidMap[userItem.user] = {}; userItem.document.forEach(doc => { cidMap[userItem.user][doc.document_name] = doc.cid; }); });
2. 生成HTML表格
方法1:动态创建DOM元素
适合直接在页面中渲染表格:
// 创建表格容器 const tableContainer = document.createElement('div'); tableContainer.className = 's-table-container'; // 创建表格 const table = document.createElement('table'); table.className = 's-table'; // 生成表头 const headerRow = document.createElement('tr'); headerRow.appendChild(document.createElement('th')); // 空表头单元格 users.forEach(user => { const th = document.createElement('th'); th.textContent = user; headerRow.appendChild(th); }); const thead = document.createElement('thead'); thead.appendChild(headerRow); table.appendChild(thead); // 生成表体 const tbody = document.createElement('tbody'); documentNames.forEach(docName => { const row = document.createElement('tr'); // 添加文档名列 const docCell = document.createElement('td'); docCell.textContent = docName; row.appendChild(docCell); // 填充各用户对应的cid users.forEach(user => { const cidCell = document.createElement('td'); cidCell.textContent = cidMap[user][docName] || ''; row.appendChild(cidCell); }); tbody.appendChild(row); }); table.appendChild(tbody); tableContainer.appendChild(table); // 将表格插入页面指定位置 document.body.appendChild(tableContainer);
方法2:拼接HTML字符串
适合直接获取HTML代码片段:
// 生成表头HTML const headerHTML = `<tr><th></th>${users.map(user => `<th>${user}</th>`).join('')}</tr>`; // 生成表体HTML const bodyHTML = documentNames.map(docName => { const cells = users.map(user => `<td>${cidMap[user][docName] || ''}</td>`).join(''); return `<tr><td>${docName}</td>${cells}</tr>`; }).join(''); // 完整表格代码 const tableHTML = ` <div class="s-table-container"> <table class="s-table"> <thead>${headerHTML}</thead> <tbody>${bodyHTML}</tbody> </table> </div> `; // 可直接输出或插入页面 console.log(tableHTML);
3. 可选样式补充
如果需要匹配示例表格的视觉效果,添加以下CSS:
.s-table-container { overflow-x: auto; margin: 1rem 0; } .s-table { border-collapse: collapse; width: 100%; max-width: 600px; } .s-table th, .s-table td { border: 1px solid #ddd; padding: 8px; text-align: left; } .s-table th { background-color: #f5f5f5; }
内容的提问来源于stack exchange,提问作者Bojan
相关产品推荐
相关产品推荐

