如何将首行存表头的JSON转为常规对象数组并在HTML中展示
一、特殊JSON结构转对象数组的方法
转换核心逻辑是把二维数组第一行作为对象的键名,后续每行的元素和键名按顺序一一对应生成单个对象,最终组合为目标数组,参考代码如下:
// 入参为你拿到的源JSON数据 function transformJson(sourceData) { // 解构出表头和数据行 const [headers, ...rows] = sourceData.values; return rows.map(row => { // 逐行把值和表头字段绑定为对象 return row.reduce((obj, value, index) => { // 可按需添加值预处理逻辑,示例为去掉字符串末尾的句号 obj[headers[index]] = value.replace(/\.$/, ''); return obj; }, {}); }); } // 调用示例 const source = { "values": [ ["name", "age", "location"], ["Alice", "28", "Florida."], ["Bob", "27", "Texas"] ] }; const targetArray = transformJson(source); // 输出结果即为你需要的对象数组格式 console.log(targetArray);
二、转换后数据渲染到HTML的方法
最常用的渲染形式为表格,参考实现如下:
- 先在HTML文件中准备容器
<table border="1" cellpadding="8" cellspacing="0"> <thead id="table-header"></thead> <tbody id="table-body"></tbody> </table>
- 编写渲染逻辑
function renderTable(dataArray) { if (!dataArray.length) return; const headerDom = document.getElementById('table-header'); const bodyDom = document.getElementById('table-body'); // 提取表头字段 const headers = Object.keys(dataArray[0]); // 渲染表头 headerDom.innerHTML = `<tr>${headers.map(h => `<th>${h}</th>`).join('')}</tr>`; // 渲染数据行 bodyDom.innerHTML = dataArray.map(item => { return `<tr>${headers.map(h => `<td>${item[h]}</td>`).join('')}</tr>`; }).join(''); } // 传入转换后的数组调用渲染方法 renderTable(targetArray);
如果需要渲染为列表、卡片等其他结构,只需修改render函数内的DOM拼接逻辑即可。
内容的提问来源于stack exchange,提问作者Rudolph Musngi
相关产品推荐
相关产品推荐

