您可以使用电子邮件地址作为键将每一行推送到 dictionary 中的数组。您将使用 JavaScript object 来执行此操作。字典将以key:value 对的形式存储您的数据,电子邮件地址为key 和values 数组,用于存储您要发送到该地址的数据。你最终会得到一个看起来有点像这样的字典:
{"email.address@domain.tld": [['data row 1', 1, 'foo'],
['data row 2', 2, 'bar']
],
"another.email@domain.tld": [['only one data row', 0, 'baz']],
"group.email@domain.tld": [['1st of many', 10, 'lorem'],
['2nd row', 20, 'ipsum'],
['3rd row', 30, 'dolor'],
['Nth row', 100, 'si amet']
]
}
因此,您从数据行中提取电子邮件地址并在字典的键中查找该电子邮件:
- 如果电子邮件存在,则将新的数据行推送到
在那把钥匙上;
- 如果没有,则创建一个新数组,电子邮件地址为
他们将数据行作为第一个元素。
一旦字典被填充,您就可以使用for(var key in dictionary){} 构造遍历键。您可以以dictionary.key 或dictionary[key] 的形式访问每个键下的值。它只是一个带有名称而不是索引的数字的数组! (实际上不是,但类比就足够了。)因此,您可以以dictionary[key][0](或dictionary.key[0])的形式访问给定键下数组的第一个元素。 而且您仍然可以使用key 中的值(在您的情况下是电子邮件地址),因此您可以写Logger.log("key = %s, values = %s", key, dictionary[key])。
代码如下所示:
/*...connect to your data source as above...*/
var info = range.getValues();
/* Create an empty JS Object to provide our dictionary.
*+ we'll add each email address as a dict key as we see it.
*+ each key will point to an array which will be the data
*+ to be entered into each email to the recipient address (the key) */
var email_data_store = {};
for (i in info) {
var col = info[i];
/*...variable assignments as above...*/
var email = col[6];
if(email != ""){
if(!(email in email_data_store)){ // Does a key matching this email already exist?
// if not, create it:
email_data_store[email] = [];
// so now we have an empty array under the key `email`
}
email_data_store[email].push(/* an array of your values */);
}
}
// now iterate over the dict to format the emails & send
for(var email in email_data_store){
/* in here, iterate over the 2D arrays in email_data_store[email]
*+ You can use array notation to address all items,
*+ so that you don't have the potential confusion of
*+ mixing array & object notation */
for(var i = 0, lim = email_data_store[email].length; i < lim; ++i){
/* format your data here */
}
MailApp.sendEmail(email, /* your formatted email body */);
}
/* whatever cleanup you want to do before ending your function */
更多文档:MDN on JS Objects