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

根据指定表头列处理服务器数据生成适配Google Sheet的二维数组

实现逻辑说明

现有代码仅完成了按指定列提取字段的基础逻辑,缺少combineHeaderData对应的商品类别合并处理,调整方案如下:

  • 先根据配置区分需要合并的类别列和普通保留列
  • 提取普通列的字段值,缺失内容自动补空
  • 针对指定合并的商品类别,汇总对应列下的所有非空商品值
  • 最终拼接自定义表头和处理后的行数据,生成可直接导入Google Sheet的二维数组

调整后完整代码

<!DOCTYPE html>
<html>
<body>
  <script>
    //*******************用户输入配置区***************************/
    // 需要合并的商品类别,支持动态调整
    var combineHeaderData = ["fruits"];
    // 需要保留的列头
    var columnHeadingsNeeded = [
      "fruits 1",
      "fruits 2",
      "fruits 3",
      "fruits 4",
      "fruits 5",
      "vegetables 1",
      "vegetables 2"
    ]
    //*******************用户输入配置区结束***************************/

    // 模拟服务器返回的原始商品数据
    var downloadedJSON = [{
        "vegetables 1": "carrot",
        "vegetables 2": "cabbage",
        "fruits 1": "banana",
        "fruits 2": "apple",
        "fruits 3": "orange",
        "nuts 1": "cashew"
      },
      {
        "vegetables 1": "beans",
        "fruits 1": "watermelon",
        "fruits 2": "apple",
        "fruits 3": "orange",
        "nuts 1": "cashew",
        "berries 1": "blueberry",
      }
    ]

    //*******************数据处理核心逻辑***************************/
    // 筛选需要合并的列和普通保留列
    const mergeCols = combineHeaderData.flatMap(category => 
      columnHeadingsNeeded.filter(col => col.startsWith(category))
    )
    const normalCols = columnHeadingsNeeded.filter(col => !mergeCols.includes(col))
    
    // 逐行处理原始数据
    let table = downloadedJSON.map(item => {
      // 提取普通列的值
      const normalValues = normalCols.map(k => item[k] ?? '')
      // 合并指定类别的所有非空商品值
      const mergedValues = combineHeaderData.map(category => {
        return columnHeadingsNeeded
          .filter(col => col.startsWith(category))
          .map(col => item[col] ?? '')
          .filter(val => val)
          .join(',')
      })
      // 按顺序返回行数据
      return [...mergedValues, ...normalValues]
    })

    // 拼接最终表头
    const finalHeader = [...combineHeaderData, ...normalCols]
    table.unshift(finalHeader)

    // 输出可直接导入Google Sheet的二维数组
    document.write(JSON.stringify(table))
  </script>
</body>
</html>

输出示例

以上述配置为例,最终输出的结构如下,可直接粘贴到Google Sheet使用:

[
  ["fruits","vegetables 1","vegetables 2"],
  ["banana,apple,orange","carrot","cabbage"],
  ["watermelon,apple,orange","beans",""]
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 22:09:02