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

如何修改Google Script App拆分多数组并合并为指定结构变量

拆分Google Apps Script中API数据提取代码的变量

我正在对接库存查询API,用Google Apps Script从返回的JSON数据中提取指定字段写入表格,原脚本如下:

function test(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var targetsheet = ss.getSheetByName("test");

  var options = {
    "method" : "GET",
    "headers" : {
      "clientId" : "1",
      "key": "1",
      "Prefer": "code=200",
      "Prefer":"dynamic=true"
    }
  }

  var text = UrlFetchApp.fetch("https://stoplight.io/mocks/flowhub/public-developer-portal/24055485/v0/locations/1/inventory",options).getContentText();
  var json = JSON.parse(text);

  var values = json.data.flatMap(({ productId, cannabinoidInformation, weightTierInformation }) => cannabinoidInformation.map(({lowerRange,name }, i) => [productId, lowerRange, name, weightTierInformation[i].name, weightTierInformation[i].gramAmount]));

  targetsheet.getRange(2, 1,values.length, values[0].length).setValues(values);
}

当前脚本输出的表格列对应字段:

  • A列:productId
  • B列:cannabinoidInformation > lowerRange
  • C列:cannabinoidInformation > name
  • D列:weightTierInformation > name
  • E列:weightTierInformation > gramAmount

我希望把原代码中单个values变量拆分为3个变量:

  1. var ci = json.data.flatMap(({cannabinoidInformation }) => cannabinoidInformation.map(({lowerRange,name }) => [lowerRange, name]));
  2. var wi = json.data.flatMap(({weightTierInformation }) => weightTierInformation.map(({name,gramAmount }) => [name, gramAmount]));
  3. var values:需要在此处整合productId、ci和wi,最终得到和原脚本一致的输出格式(A到E列顺序不变)

实现方案

直接单独提取ci和wi会丢失每个条目对应的productId,以及cannabinoidInformation和weightTierInformation之间的索引关联,所以需要先为每个数据项处理对应关系,再拆分变量:

// 先处理每个data项,保留productId及对应ci、wi的关联
var processedData = json.data.map(item => ({
  productId: item.productId,
  ci: item.cannabinoidInformation.map(({lowerRange, name}) => [lowerRange, name]),
  wi: item.weightTierInformation.map(({name, gramAmount}) => [name, gramAmount])
}));

// 拆分出单独的ci和wi变量
var ci = processedData.flatMap(item => item.ci);
var wi = processedData.flatMap(item => item.wi);

// 整合得到最终values,保持原输出格式
var values = processedData.flatMap(item => 
  item.ci.map((ciItem, i) => [
    item.productId, 
    ...ciItem, 
    ...item.wi[i]
  ])
);

这样既拆分出了单独的ci和wi变量,又保证了values的输出格式和原脚本完全一致,同时保留了各字段的关联关系。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 20:20:25