如何通过Google Apps Script为Google Sheets添加指定JSON子字段至D-E列
修改后的Google Apps Script代码
以下是满足需求的完整代码,已添加weightTierInformation下的name和gramAmount字段到表格D-E列:
function test(e) { var ss = SpreadsheetApp.getActiveSpreadsheet(); var targetsheet = ss.getSheetByName("test"); var options = { //"async": true, //"crossDomain": true, "method": "GET", "headers": { "clientId": "1", "key": "1", "Prefer": "code=200,dynamic=true" // 合并重复的Prefer字段,避免覆盖 } }; var text = UrlFetchApp.fetch("https://stoplight.io/mocks/flowhub/public-developer-portal/24055485/v0/locations/1/inventory", options).getContentText(); var json = JSON.parse(text); // 嵌套处理cannabinoid和weightTier的组合,生成包含5个字段的行数据 var values = json.data.flatMap(({ productId, cannabinoidInformation, weightTierInformation }) => cannabinoidInformation.flatMap(cannabinoid => weightTierInformation.map(weightTier => [productId, cannabinoid.lowerRange, cannabinoid.name, weightTier.name, weightTier.gramAmount] ) ) ); // 写入数据到A-E列,从第2行开始 targetsheet.getRange(2, 1, values.length, values[0].length).setValues(values); }
关键修改说明
- 修复请求头问题:原代码中重复定义
Prefer字段,后定义的会覆盖前一个,现已合并为"Prefer": "code=200,dynamic=true",确保两个偏好设置都生效 - 新增字段解构:在
flatMap的对象解构中加入weightTierInformation,获取该字段的数组数据 - 嵌套生成行数据:通过两层
flatMap+map的组合,将每个产品的大麻素信息与重量等级信息进行全组合,确保每一行同时包含两类信息的对应项 - 自动适配列数:写入表格时使用
values[0].length自动适配新的列数(从3列变为5列),无需手动修改范围参数
内容的提问来源于stack exchange,提问作者Kal El
相关产品推荐
相关产品推荐

