我正在使用脚本编辑器在 Google 表单中收集调查结果。我的脚本看起来像:
function myFunction() {
var formResponses = FormApp.getActiveForm().getResponses();
var allResponses=[];
for (var j = 0; j < formResponses.length; j++) {
var formResponse = formResponses[j];
var itemResponses = formResponse.getItemResponses();
for (var i = 0; i < itemResponses.length; i++) {
var itemResponse = itemResponses[i];
allResponses.push( itemResponse.getResponse() );
}
}
var jsonRes=JSON.stringify(allResponses);
MailApp.sendEmail("noreply@mydomain.com", "Survey Results", jsonRes);
}
这工作得很好。现在我想添加一些统计信息,例如计算每个响应的结果数。为此,我想以Map
一种简单的方式使用 ECMA6,例如:
// flatten the array
var words=allResponses.map(a => a.join(',')).join(',').split(',')
// map reduce and calculate occurrences of the map keys
var chart=[...words.reduce( (m, v) => m.set(v, (m.get(v) || 0) + 1), new Map() )].sort((a,b) => b[1]-a[1])
chart=chart.map(function(i) { return i.join(",")})
chart=chart.map(function(item,index) { return ((index+1)+","+item)})
var jsonRes=JSON.stringify(chart);
这只会输出我的回复列表,如
[
"1,responseA,1024",
"2,responseA,956",
"3,responseA,433"
]
等等
出乎意料的是,这会导致谷歌脚本编辑器出错,所以我虽然它是 ECMA6 箭头运算符,所以我已经恢复了功能:
var words=allResponses.map(function(a) { return a.join(',') } ).join(',').split(',');
var map=words.reduce(function(m,v) { return m.set(v, (m.get(v) || 0) + 1)}, new Map() );
// convert back Map entries to Array
var chart = Array.from(map.entries());
chart.sort(function(a,b){ return (b[1]-a[1])});
var jsonRes=JSON.stringify(chart);
有趣的故事:Map
对象是undefined
ergo Google Script 不支持ECMAScript6
,或者我做错了什么,是吗?
[更新]
由于以下响应,这是有效的 Google Script 解决方案:
function myFunction() {
var formResponses = FormApp.getActiveForm().getResponses();
var allResponses=[];
for (var j = 0; j < formResponses.length; j++) {
var formResponse = formResponses[j];
var itemResponses = formResponse.getItemResponses();
for (var i = 0; i < itemResponses.length; i++) {
var itemResponse = itemResponses[i];
allResponses.push( itemResponse.getResponse() );
}
}
var words=allResponses.map(function(a) { return a.join(',') }).join(',').split(',');
var chart = words.reduce(function(m,v) {m[v] = m[v] ? m[v] + 1 : 1; return m;}, {}); // Added
chart = Object.keys(chart).map(function(k) {return [k, chart[k]]}).sort(function(a,b) {return b[1]-a[1]}); // Added
chart=chart.map(function(i) { return i.join(",")})
chart=chart.map(function(item,index) { return ((index+1)+","+item)})
var jsonRes=JSON.stringify(chart);
MailApp.sendEmail("noreply@mydomain.com", "Survey Results", jsonRes);
}