如何用JavaScript基于对象数组生成动态表格?
动态生成基于对象数组的HTML表格
现有如下对象数组(示例):
[ { "_id": "6937729", "affiliate_url": "https://event.2performant.com/events/click?ad_type=product_store&unique=116db0312&aff_code=4b8685e94&campaign_unique=4b9a6d5ea", "availability": true, "brand": "SensoPRO Milano", "descriptionDDDD": "Botosi Tratament Parafina Soft Ingrid SensoPRO Milano sunt alegerea perfecta pentru a evita aparitia calcaielor crapate sau a deshidratarii pielii picioarelor! Botosii SPA sunt creati din material textil, flausat. Fiind flausati, mentin o temperatura constanta a parafinei atunci cand sunt utilizati. Folosind Botosi Tratament Parafina Soft Ingrid SensoPRO Milano vei obtine intretinerea picioarelor, dar vei avea parte si de momente de relaxare! ATENTIE! Acesti botosi nu au parafina inclusa, aceasta se cumpara separat!", "id": "6937729", "image_link": [ "https://cdnmpro.com/677236441/p/raw/6/botosi-tratament-parafina-soft-ingrid-sensopro-milano~7633286.jpg", "https://cdnmpro.com/677236441/p/raw/5/botosi-tratament-parafina-soft-ingrid-sensopro-milano~7633285.jpg", "https://cdnmpro.com/677236441/p/raw/7/botosi-tratament-parafina-soft-ingrid-sensopro-milano~7633287.jpg", "https://cdnmpro.com/677236441/p/raw/8/botosi-tratament-parafina-soft-ingrid-sensopro-milano~7633288.jpg", "https://cdnmpro.com/677236441/p/raw/5/botosi-tratament-parafina-soft-ingrid-sensopro-milano~7643575.jpg" ], "link": "https://www.kitunghii.ro/parafina-cosmetica-2/botosi-tratament-parafina-soft-ingrid-sensopro-milano?utm_source=portal&utm_medium=web&utm_campaign=2parale", "price": "19.9", "product type": "Epilare", "test_value_name1": "test_content_value1", "test_value_name2": "test_content_value2", "title": "Botosi Tratament Parafina Soft Ingrid SensoPRO Milano", "updated_at": "2022-08-31T12:29:56.000000Z", "date_upd": 1665255561 }, { "_id": "6937887", "affiliate_url": "https://event.2performant.com/events/click?ad_type=product_store&unique=5cd952501&aff_code=4b8685e94&campaign_unique=4b9a6d5ea", "availability": true, "brand": "SensoPRO Milano", "descriptionDDDD": "Magnet Cat Eye Dublu pentru Oja SensoPRO Milano, accesorii pentru unghii, se adreseaza in mod special ojelor permanente Magnetto pentru Cat Eye Effect, in realizarea efectului special de \"Cat Eyes\".", "id": "6937887", "image_link": [ "https://cdnmpro.com/677236441/p/raw/4/magnet-cat-eye-dublu-pentru-oja-sensopro-milano~7618904.jpg", "https://cdnmpro.com/677236441/p/raw/3/magnet-cat-eye-dublu-pentru-oja-sensopro-milano~7618903.jpg" ], "link": "https://www.kitunghii.ro/accesorii-manichiura/magnet-cat-eye-dublu-pentru-oja-sensopro-milano?utm_source=portal&utm_medium=web&utm_campaign=2parale", "price": "9.9", "product type": "Accesorii Unghii", "test_value_name1": "test_content_value1", "test_value_name2": "test_content_value2", "title": "Magnet Cat Eye Dublu pentru Oja SensoPRO Milano", "updated_at": "2022-08-31T12:29:56.000000Z", "date_upd": 1665248423 } ]需要基于该数组生成HTML表格,表头为对象的键,列值为对应键的取值。注意:实际场景中对象的键数量不固定,可能是2个到200个不等。
已尝试过遍历数组和对象键的代码,但需要完整的表格生成实现方案。
实现步骤
核心逻辑是先提取所有唯一表头字段,再遍历数组生成每行内容,同时处理特殊类型的值(如数组、布尔值),确保表格展示友好。
1. 提取表头字段
如果数组中对象的键不完全一致,需要合并所有对象的键并去重;若确定所有对象键完全相同,直接取第一个对象的键即可。
2. 构建表格DOM结构
- 创建
<table>容器,添加表头<thead> - 遍历表头字段生成
<th>单元格 - 遍历数组每个对象,生成
<tr>行,再按表头字段匹配对应值,生成<td>单元格
3. 处理特殊值
- 数组类型:转为可展示的缩略图或文本列表
- 布尔值:转为"可用/不可用"这类友好文本
- 空值:统一显示短横线
-
完整代码示例
// 假设数据来源是response.data.data const products = response.data.data; // 步骤1:提取所有唯一表头字段 const allKeys = [...new Set(products.flatMap(item => Object.keys(item)))]; // 步骤2:创建表格元素 const table = document.createElement('table'); table.border = 1; // 可选:添加边框提升可读性 // 生成表头 const thead = document.createElement('thead'); const headerRow = document.createElement('tr'); allKeys.forEach(key => { const th = document.createElement('th'); th.textContent = key; headerRow.appendChild(th); }); thead.appendChild(headerRow); table.appendChild(thead); // 生成表体 const tbody = document.createElement('tbody'); products.forEach(item => { const row = document.createElement('tr'); allKeys.forEach(key => { const td = document.createElement('td'); let value = item[key]; // 处理不同类型的值 if (Array.isArray(value)) { // 图片数组转为带缩略图的链接 value = value.map(url => `<a href="${url}" target="_blank"><img src="${url}" width="50" height="50"></a>`).join('<br>'); td.innerHTML = value; } else if (typeof value === 'boolean') { // 布尔值转为友好文本 td.textContent = value ? '可用' : '不可用'; } else if (typeof value === 'object' && value !== null) { // 复杂对象转为JSON字符串展示 td.textContent = JSON.stringify(value); } else { // 普通值直接显示,空值用短横线替代 td.textContent = value || '-'; } row.appendChild(td); }); tbody.appendChild(row); }); table.appendChild(tbody); // 将表格添加到页面指定容器 document.body.appendChild(table);
简化版:HTML字符串拼接
如果不需要操作DOM元素,直接拼接HTML字符串插入页面:
const products = response.data.data; const allKeys = [...new Set(products.flatMap(item => Object.keys(item)))]; // 拼接表头 let tableHtml = '<table border="1"><thead><tr>'; allKeys.forEach(key => { tableHtml += `<th>${key}</th>`; }); tableHtml += '</tr></thead><tbody>'; // 拼接表体 products.forEach(item => { tableHtml += '<tr>'; allKeys.forEach(key => { let value = item[key]; let cellContent = '-'; if (Array.isArray(value)) { cellContent = value.map(url => `<a href="${url}" target="_blank"><img src="${url}" width="50" height="50"></a>`).join('<br>'); } else if (typeof value === 'boolean') { cellContent = value ? '可用' : '不可用'; } else if (value !== undefined && value !== null) { cellContent = value; } tableHtml += `<td>${typeof cellContent === 'string' ? cellContent : JSON.stringify(cellContent)}</td>`; }); tableHtml += '</tr>'; }); tableHtml += '</tbody></table>'; // 插入到页面容器 document.getElementById('table-container').innerHTML = tableHtml;
内容的提问来源于stack exchange,提问作者Shibbir
相关产品推荐
相关产品推荐

