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

Google Apps Script按表头将表格行转换为键值对的实现问题

问题原因

原有代码逻辑为按表头字段创建对应数组,将所有行的同字段值统一存入该数组,最终输出按字段分组的结构,与「每行对应一个独立对象」的需求不符。

实现方案

先提取表头数组,再遍历每一行数据,将行内每个位置的值与对应位置的表头做映射,生成单个行对象,最终将所有行对象汇总为数组即可。

表格示例

最终可用代码

function tableToObject() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const transactionSheet = ss.getSheetByName('Transactions');
  const lastRow = transactionSheet.getLastRow();
  const lastColumn = transactionSheet.getLastColumn();
  const values = transactionSheet.getRange(1, 1, lastRow,lastColumn).getValues();
  // 按需提取表格列,可根据你实际的表格列位置调整取值规则
  const [headers, ...originalData] = values.map(([,b,,d,e,,,,,,,,,,,p,q,r,s]) => [b,d,e,p,q,r,s]);
  // res即为你要求的每行对应一个独立对象的输出结果
  const res = originalData.map(r => headers.reduce((o, h, j) => Object.assign(o, { [h]: r[j] }), {}));
  console.log(res)

  // 可选功能:按分类+月份+年份维度聚合金额,不需要可直接删除
  const result = [...res.reduce((r, o) => {
    const key = o.Category + '_' + o.Month + '_' + o.Year
    const item = r.get(key) || Object.assign({}, o, {
      Amount: 0,
    })
    item.Amount += o.Amount
    item.Key = key
    return r.set(key, item)
  }, new Map).values()]
  console.log(result)
}

预期输出格式参考

[{
  "date": "1/4/2019",
  "category": "Source A",
  "amount": "100",
  "month": "January",
  "year": "2019",
  "group": "COGS",
  "debit/credit": "Credit",
},  {
  "date": "1/4/2019",
  "category": "Source A",
  "amount": "100",
  "month": "January",
  "year": "2019",
  "group": "COGS",
  "debit/credit": "Credit",
}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:54:03