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

如何将Sheets.Spreadsheets.Values.get()返回的undefined转为null?

解决Google Sheets API返回undefined转null及数据筛选排序问题

问题分析

原代码存在几个关键问题:

  • 变量名不匹配:srcSpreadsheetId未定义,应改为sourceid
  • 列索引对应错误:第55列对应数组索引54(A列为索引0),原代码误写为55,导致筛选逻辑偏离需求
  • 未处理行数据长度不足的情况:部分行可能未填满57列,直接访问索引会因undefined报错
  • Sheets.Spreadsheets.Values.update参数格式错误,无需嵌套多层结构

解决方案

  1. 将undefined转为null:遍历每一行数据,补全到57列长度,把undefined替换为null,避免索引访问报错
  2. 修正列索引:严格对应第N列→索引N-1的关系
  3. 编写正确筛选逻辑:判断第55列(索引54)非空、第56列(索引55)为空
  4. 添加日期排序:将第57列(索引56)的日期字符串转为Date对象,按时间排序
  5. 修正API调用参数:符合Sheets API的参数格式要求

完整代码

function myFunction() {
  const sourceid = '你的源表格ID';
  const targetid = '你的目标表格ID';
  const source_range = "Source File!A2:BE";
  const destination_range = "Target File!A2:BE";

  // 获取源数据,处理undefined为null并补全列数到57列
  const response = Sheets.Spreadsheets.Values.get(sourceid, source_range);
  const rawData = response.values || []; // 处理空数据情况
  const processedData = rawData.map(row => {
    const filledRow = [...row];
    // 补全到57列(A到BE共57列),不足的用null填充
    while (filledRow.length < 57) {
      filledRow.push(null);
    }
    // 将undefined转为null
    return filledRow.map(cell => cell === undefined ? null : cell);
  });

  // 筛选:第55列(索引54)非空,第56列(索引55)为空
  const filteredData = processedData.filter(row => {
    const col55 = row[54];
    const col56 = row[55];
    return (col55 !== null && col55 !== '') && (col56 === null || col56 === '');
  });

  // 按第57列(索引56,日期列)排序,升序排列
  filteredData.sort((a, b) => {
    const dateA = new Date(a[56]);
    const dateB = new Date(b[56]);
    return dateA - dateB;
  });

  // 写入目标表格
  if (filteredData.length > 0) {
    Sheets.Spreadsheets.Values.update(
      { values: filteredData },
      targetid,
      destination_range,
      { valueInputOption: "USER_ENTERED" }
    );
  } else {
    console.log("没有符合条件的数据");
  }
}

关键说明

  • 补全列数:确保每一行都有57个元素,避免后续访问索引时出现undefined
  • undefined转null:统一空值判断标准,null比undefined更适合用于条件判断
  • 日期排序:注意表格中的日期需为可被new Date()解析的格式,若为自定义格式可能需要额外处理
  • 空数据处理:添加response.values || []避免无数据时出现报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:01:04