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

如何使用属性映射将二维数组转换为指定嵌套结构的JSON对象

二维数组转嵌套JSON对象实现方案

实现代码

function arrToJSON(headers, data) {
  const output = [];
  // 遍历每一行原始数据
  data.forEach(row => {
    const cObj = {};
    // 遍历每个映射表头
    headers.forEach((header, itemIndex) => {
      const keyParts = header.split('.');
      // 临时指针,跟踪当前操作的嵌套对象层级
      let current = cObj;
      keyParts.forEach((part, idx) => {
        // 最后一个key片段直接赋值
        if (idx === keyParts.length - 1) {
          current[part] = row[itemIndex];
          return;
        }
        // 非末尾片段不存在时自动初始化空对象
        if (!current[part]) {
          current[part] = {};
        }
        // 指针移动到子对象层级
        current = current[part];
      });
    });
    output.push(cObj);
  });
  return output;
}

// 测试调用
var keys = ['id', 'title', 'customer.id', 'customer.name', 'customer.phone.home', 'customer.phone.mobile' ];
var data = [
  [1, 'Task 1', 'C1', 'Customer 1', '999', '8888'],
  [2, 'Task 2', 'C2', 'Customer 2', '333', '5555']
];
console.log(arrToJSON(keys, data));

逻辑说明

  • 用临时指针替代递归处理嵌套结构,代码复杂度更低、性能更好
  • 自动适配任意层级的带.嵌套字段,不需要提前定义嵌套结构
  • 输出结果完全符合要求的嵌套JSON格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:18:07