Google Apps Script调用食品API时的动态属性适配问题咨询
解决Google Apps Script中API属性动态处理问题
核心思路
避免直接访问可能不存在的嵌套属性,通过安全访问机制处理属性缺失的情况,同时结合列头与属性路径的映射,实现动态适配不同产品的属性差异。
方法1:使用可选链操作符(?.)和空值合并运算符(??)
Google Apps Script启用V8引擎后支持ES6+语法,可选链?.会在属性不存在时返回undefined,不会抛出错误;空值合并运算符??仅在值为null/undefined时返回默认值,比||更精准。
修改你的空值处理代码为:
product?.annualEnergyConsumptionNumber?.[0]?.data ?? ' '
- 若
product本身不存在,直接返回' ' - 若
annualEnergyConsumptionNumber属性不存在/为空数组,返回' ' - 若数组元素
[0]不存在,返回' ' - 仅当所有层级都存在且
data有值时,返回data的内容
方法2:自定义安全取值函数(兼容旧环境)
如果脚本运行环境不支持可选链,可写一个通用函数安全获取嵌套属性:
function getSafe(obj, path, defaultValue = ' ') { return path.split('.').reduce((current, key) => { // 处理数组索引格式,比如"annualEnergyConsumptionNumber[0]" if (key.includes('[')) { const arrKey = key.split('[')[0]; const index = parseInt(key.split('[')[1].replace(']', ''), 10); return current && current[arrKey] ? current[arrKey][index] : undefined; } return current && current[key] ? current[key] : undefined; }, obj) ?? defaultValue; }
使用示例:
// 获取product.annualEnergyConsumptionNumber[0].data,不存在则返回' ' const energyData = getSafe(product, 'annualEnergyConsumptionNumber[0].data', ' ');
方法3:结合列头实现动态批量处理
由于表格列头与API属性一一对应,建议将列头和属性路径做成映射表,循环处理每一列,避免重复写安全访问代码:
// 定义列头与API属性路径的映射 const columnMapping = [ { header: '产品名称', path: 'productName' }, { header: '年能耗数据', path: 'annualEnergyConsumptionNumber[0].data' }, { header: '生产批次', path: 'productionBatch' }, // 补充其他列的映射... ]; // 填充表格的核心函数 function fillProductData(productSerial) { // 调用API获取产品数据(替换为你的API调用逻辑) const product = fetchProductDataFromAPI(productSerial); // 获取目标表格 const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('产品数据'); // 写入列头(仅初始化时需要,可根据逻辑调整) const headers = columnMapping.map(item => item.header); sheet.getRange(1, 1, 1, headers.length).setValues([headers]); // 生成要填充的数据行 const rowData = columnMapping.map(item => { return getSafe(product, item.path, ' '); }); // 写入表格到下一行 const nextRow = sheet.getLastRow() + 1; sheet.getRange(nextRow, 1, 1, rowData.length).setValues([rowData]); }
额外注意事项
- 启用V8引擎:在脚本编辑器中点击
运行 > 启用新的Apps Script运行时,确保支持现代语法。 - 错误捕获:在API调用和数据处理外层加
try-catch,避免单个产品的异常中断整个脚本:
function fillProductData(productSerial) { try { // 现有代码逻辑... } catch (e) { console.error(`处理产品${productSerial}时出错: ${e.message}`); // 将错误信息写入表格对应行 const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('产品数据'); const nextRow = sheet.getLastRow() + 1; sheet.getRange(nextRow, 1).setValue(`错误:${e.message}`); } }
内容的提问来源于stack exchange,提问作者YmlScripts
相关产品推荐
相关产品推荐

