如何在Google Apps Script中合并过滤后数组的子数组元素
解决Google Apps Script中合并过滤后数组对应元素的问题
问题场景与需求
- 用户通过含子表的表单提交多条数据,需借助Google Apps Script生成Google Doc模板,根据唯一ID拉取对应数据,将子表多列数据合并(用CHAR10换行堆叠)后插入模板指定位置。
- 已成功过滤出对应唯一ID的行,但
map、flat()、flatMap()函数无法正常使用(甚至不被识别),需实现将过滤后的子数组对应元素合并为新数组的功能。
数据示例
原始数据:
Joe blue coffee steak fish Jerry yellow soda steak fish Joe black water chicken lettuce John green water steak fish
过滤后数据:
Joe blue coffee steak fish Joe black water chicken lettuce
过滤后数组:
[["joe", "blue", "coffee", "steak", "fish"],["joe", "black", "water", "chicken", "lettuce"]]
期望生成的新数组(用CHAR10换行堆叠):
["joe\njoe", "blue\nblack", "coffee\nwater", "steak\nchicken", "fish\nlettuce"]
问题原因
Google Apps Script基于ES5环境运行,部分ES6+数组方法(如flatMap)默认不支持;同时你的代码中map()未传入回调函数,本身存在语法错误。
解决方案
方法1:传统循环实现合并(推荐)
直接遍历列索引,收集每一列的元素并按需求合并,逻辑清晰且适配ES5环境:
function createDoc() { // 修正ID引号缺失问题,复制模板到目标文件夹 const docTemplate = DriveApp.getFileById('1vqBztNAJZMU5HQPBEN'); const destinationFolder = DriveApp.getFolderById('1Gk_5a2EFTA'); const newDoc = docTemplate.makeCopy('Test Copy', destinationFolder); // 获取表格数据 const ssId = '1wBr4wBu9OZ73Z1FBf6j5pongzjHMVfjxMdrNwHyPpUk'; const appsheetFormat = SpreadsheetApp.openById(ssId).getSheetByName('Appsheet format'); const appsheetFormatTable = appsheetFormat.getDataRange().getValues(); // 获取唯一ID(二选一:表单触发用注释行,手动运行用下一行) // const uniqueId = e.response.user.responses[0].get("Unique ID"); const uniqueId = appsheetFormatTable.slice(-1)[0][0]; const moderation = SpreadsheetApp.openById(ssId).getSheetByName('Moderation Services'); const moderationTable = moderation.getDataRange().getValues(); const moderationRows = moderationTable.filter(row => row[0] === uniqueId); // 核心合并逻辑 let combinedModerationRows = []; if (moderationRows.length > 0) { const colCount = moderationRows[0].length; // 遍历每一列,收集对应元素并用换行符拼接 for (let col = 0; col < colCount; col++) { const mergedCol = moderationRows.map(row => row[col]).join('\n'); combinedModerationRows.push(mergedCol); } } console.log(combinedModerationRows); // 后续可将combinedModerationRows插入Doc模板指定位置 }
方法2:添加ES6方法兼容(可选)
若一定要使用flat、flatMap等ES6方法,可在脚本开头添加polyfill补全:
// 补全flatMap方法 if (!Array.prototype.flatMap) { Array.prototype.flatMap = function(callback) { return this.map(callback).reduce((acc, val) => acc.concat(val), []); }; } // 补全flat方法 if (!Array.prototype.flat) { Array.prototype.flat = function(depth = 1) { return this.reduce(function (flat, toFlatten) { return flat.concat((Array.isArray(toFlatten) && depth>1) ? toFlatten.flat(depth-1) : toFlatten); }, []); }; }
额外修正点
- 代码中存在引号缺失问题(如
DriveApp.getFileById('1vqBztNAJZMU5HQPBEN);未闭合单引号),必须修正否则脚本报错。 - 重复声明
uniqueId变量,需保留其中一个(根据触发方式选择)。
内容的提问来源于stack exchange,提问作者Richard Liu
相关产品推荐
相关产品推荐

