如何将JS Map转为console.log输出格式的可读字符串 兼容Google Apps Script
Google Apps Script 中将Map转为结构化字符串的实现方法
直接使用GAS内置的JSON.stringify()方法即可实现需求,无需引入额外依赖:
let mapObject = new Map(); mapObject.set("one", "file1"); mapObject.set("two", "file2"); mapObject.set("three", "file3"); // 序列化得到结构化字符串 const structuredMapStr = JSON.stringify([...mapObject.entries()]); // 直接输出和console.log([...mapObject.entries()])结构完全一致 console.log(structuredMapStr); // 输出:[["one","file1"],["two","file2"],["three","file3"]] // 拼接字符串时也不会丢失结构 console.log("This is a map: " + structuredMapStr); // 输出:This is a map: [["one","file1"],["two","file2"],["three","file3"]]
如果需要和你示例中控制台输出的单引号、逗号后带空格的格式1:1匹配,可以在序列化后做简单替换:
const formattedMapStr = JSON.stringify([...mapObject.entries()]) .replaceAll('","', "', '") .replaceAll('[["', "[['") .replaceAll('"]]', "']]") .replaceAll('"],["', "'], ['"); console.log(formattedMapStr); // 输出:[['one', 'file1'], ['two', 'file2'], ['three', 'file3']]
如果你的GAS使用的是旧版Rhino运行时不支持
replaceAll,可以将替换语句改为正则全局匹配的形式:const formattedMapStr = JSON.stringify([...mapObject.entries()]) .replace(/","/g, "', '") .replace(/\[\["/g, "[['") .replace(/"]]/g, "']]") .replace(/"],\["/g, "'], ['");
说明
字符串拼接时数组会自动触发toString()方法,该方法会递归打平所有嵌套数组元素并用逗号连接,因此会丢失结构化格式,使用序列化方法可以完整保留嵌套结构。
内容的提问来源于stack exchange,提问作者David Leal
相关产品推荐
相关产品推荐

