如何获取数组中对象的键并将数据拆分为表头和表值生成表格?
实现方法
核心思路
- 提取表头:取响应数组第一个元素的所有键作为表头,结构不一致的场景可遍历所有元素的键去重得到全量表头
- 提取表值:遍历数组每个元素,按表头顺序提取对应属性值组成行数据
代码实现
基础数据处理
// 后端返回的原始响应数据 const responseData = [ { id: "haskjdhak", name: "lorem ipsun 1", desc: "any description 1" }, { id: "78khasc", name: "lorem ipsun 2", desc: "any description 2" }, { id: "56jkjn", name: "lorem ipsun 3", desc: "any description 3" } ]; // 提取表头(所有对象结构一致的场景) const tableHeaders = responseData.length ? Object.keys(responseData[0]) : []; // 提取表值 const tableRows = responseData.map(item => tableHeaders.map(key => item[key]));
DOM渲染示例(可选)
如果需要直接渲染成页面DOM表格,可以用以下代码:
const table = document.createElement('table'); // 渲染表头 const thead = document.createElement('thead'); thead.innerHTML = `<tr>${tableHeaders.map(key => `<th>${key}</th>`).join('')}</tr>`; table.appendChild(thead); // 渲染表体 const tbody = document.createElement('tbody'); tbody.innerHTML = tableRows.map(row => `<tr>${row.map(val => `<td>${val}</td>`).join('')}</tr>`).join(''); table.appendChild(tbody); // 插入到页面中 document.body.appendChild(table);
兼容场景处理
如果响应数组中的对象属性存在差异,可使用全量表头提取方法:
// 遍历所有对象的键,去重后得到完整表头 const tableHeaders = [...new Set(responseData.flatMap(item => Object.keys(item)))];
内容的提问来源于stack exchange,提问作者riki yudha
相关产品推荐
相关产品推荐

