You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript从HTML表格抓取的字符串数组生成指定结构的JSON

实现线性数组到目标JSON格式的转换

当然可以实现!你的思路方向完全正确,只需要补充循环遍历的逻辑来分组处理数据,就能轻松完成转换。下面是具体的实现方案:

基础实现(固定2个表头)

针对你给出的示例数据,我们可以这样写:

var data = ["header1", "header2", "a1", "a2", "b1", "b2", "c1", "c2"];

// 提取前两个元素作为表头
const headers = data.slice(0, 2);
const jsonObj = [];

// 从第3个元素开始,每2个元素为一组构建对象
for (let i = 2; i < data.length; i += 2) {
  const row = {};
  // 给对象绑定表头对应的字段值
  row[headers[0]] = data[i];
  row[headers[1]] = data[i + 1];
  jsonObj.push(row);
}

// 此时jsonObj就是你想要的格式
console.log(jsonObj);

运行这段代码后,jsonObj的结构完全符合你的要求:

[ { "header1":"a1", "header2":"a2" }, { "header1":"b1", "header2":"b2" }, { "header1":"c1", "header2":"c2" } ]

通用扩展(支持任意数量的表头)

如果以后表头数量可能变化,比如3个或更多,可以改成更通用的写法,适配不同的表头数量:

var data = ["header1", "header2", "header3", "a1", "a2", "a3", "b1", "b2", "b3"];

const headerCount = 3; // 这里定义表头的数量
const headers = data.slice(0, headerCount);
const jsonObj = [];

// 按表头数量分组遍历数据
for (let i = headerCount; i < data.length; i += headerCount) {
  const row = {};
  // 逐个绑定表头和对应的数据值
  for (let j = 0; j < headerCount; j++) {
    row[headers[j]] = data[i + j];
  }
  jsonObj.push(row);
}

这个版本不管表头是2个、3个还是更多,只要数据是[表头1, 表头2, ..., 行1数据1, 行1数据2, ..., 行2数据1, 行2数据2, ...]的结构,都能正确转换成目标JSON。

内容的提问来源于stack exchange,提问作者sqlQueryAll

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 20:22:32