【问题标题】:Add contact if contact does not exist under google contacts with “ContactsApp.getContact”如果联系人在谷歌联系人下不存在,则添加联系人,使用“ContactsApp.getContact”
【发布时间】:2020-11-22 23:50:33
【问题描述】:

我在Check if contact exists under google contacts with "ContactsApp.getContact" 找到了以下代码作为对同一问题的回复,但遇到了一些问题。我正在尝试创建一个 Google 脚本来检查 Google 调查的受访者是否已经在“系统组:我的联系人”中拥有一张联系人卡片,如果没有,请创建一个联系人卡片,然后添加他们的电话号码。

我已更新以下代码以引用我的字段,但收到 if(emailjson[email.toLowerCase()].id) 行的错误 - 这是为了检查该联系人是否存在:

TypeError:无法从未定义中读取属性“id”。 (第 36 行,文件“代码”)

我认为 IF 语句有问题,但我对 Javascript(或 JSON)并不完全熟悉。作为 Excel 和 Access 人员,我习惯于 IF 语句中的 IF 为空,然后执行此操作,因此我尝试添加 === undefined,将代码更改为 if(emailjson[email.toLowerCase()].id === undefined),但这并没有解决问题。在查看执行记录时,它一碰到没有名片的人就挂断了。

如果我从电子表格的开头删除新联系人并返回到原始代码(不带 === undefined),那么它会为已经有卡片的每个人创建重复的联系人卡片,直到它到达下一个人谁是新的,然后又出错了。

对于已经有名片的人,如果电子表格中的电话号码只是数字,我也会在下一行收到错误消息,if(!emailjson[email.toLowerCase()]['phones'][phone.replace(/[_)(\s.-]/g,'')]) {

TypeError:在对象 2024313437 中找不到函数替换。(第 37 行,文件“代码”)

如果我为电话号码添加格式,那么它不会引发错误(尽管正如我之前提到的,它会创建一个重复的联系人)。奇怪的是,我之后运行 emailsasJSON 函数,它只显示一张联系人卡片而不是重复卡片,即使在 Google 联系人屏幕上我每次尝试运行脚本时都会看到一张联系人卡片。

提前感谢您的想法。

function emailsasJSON() {
  
 var emailjson = {}
  var myContacts = ContactsApp.getContactGroup('System Group: My Contacts').getContacts();
  for (var i = 0; i < myContacts.length; i++) {
    var emails = myContacts[i].getEmails();
    var phonesobj = myContacts[i].getPhones();
    var phones = {}
    for (var j = 0; j < phonesobj.length; j++) {
       phones[phonesobj[j].getPhoneNumber().replace(/[_)(\s.-]/g,'')] = 1;
    }
    for (var j = 0; j < emails.length; j++) {
      emailjson[emails[j].getAddress().toLowerCase()] = {id: myContacts[i].getId(), phones:  phones};
      
    }
  }
  Logger.log(JSON.stringify(emailjson))
  return emailjson;
}

function addClient() {
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheetNew = ss.getActiveSheet(); 

 var clientsgroup = ContactsApp.getContactGroup('System Group: My Contacts')

//this is where we will insert the function from above to get the emailjson obj
 var emailjson = emailsasJSON()

 var contactarray = sheetNew.getDataRange().getValues();
 for (var i = 1 ; i < contactarray.length; i++){
   var name = contactarray[i][1]
   var email = contactarray[i][4]
   var phone = contactarray[i][3]
   
   if(emailjson[email.toLowerCase()].id) { //check if email exists
     if(!emailjson[email.toLowerCase()]['phones'][phone.replace(/[_)(\s.-]/g,'')]) { //if email exists but phone doesn't, add phone
         
     ContactsApp.getContactById(emailjson[email.toLowerCase()].id).addPhone(ContactsApp.Field.MOBILE_PHONE, phone)
     emailjson[email.toLowerCase()]['phones'][phone.replace(/[_)(\s.-]/g,'')] = 1; //add it to the emailjson object in case there are more iterations of this contact in the sheet
     } 
   } else { //add new contact if it doesn't exist
   
    var newcontact = ContactsApp.createContact(name.split(' ')[0],name.split(' ')[1], email)
    newcontact.addPhone(ContactsApp.Field.MOBILE_PHONE, phone)
    emailjson[email.toLowerCase()]['id'] = newcontact.getId();
    emailjson[email.toLowerCase()]['phones'][phone.toString().replace(/[_)(\s.-]/g,'')] = 1;
    clientsgroup.addContact(newcontact)
     }
  }
}

样本数据:

【问题讨论】:

  • 您能否为您的 google 表格和联系人组中的值添加示例?
  • 如果同时记录 emailjson 和电子邮件数组 Logger.log(emailjson, emailjosn[email.toLowercase()].id),会得到什么?
  • @MateoRandwolf - Logger.log(emailjson,emailjson[emails.toLowerCase()].id) 返回 > 类型错误:在对象 EmailField 中找不到函数 toLowerCase。如果我删除.toLowerCase(),那么我会得到 > TypeError: Cannot read property "id" from undefined。 (第 18 行,文件“代码”)
  • @HarshanaSerasinghe - 按要求添加示例数据。

标签: javascript google-apps-script google-api google-contacts-api


【解决方案1】:

您的主要问题是您的函数emailsasJSON() 对 json 对象进行了字符串化(即它是一个字符串),因此您无法成功访问 JSON 对象的密钥对值。为了解决这个问题,我只是解析了对象以确保它是一致的,但只要你不把它转换成字符串就可以了。

下一个变化是在第一个 if 条件下。您实际上不需要检查 id 来查看元素是否存在,因为只需检查元素本身就可以完成这项工作(尽管检查 id 也可以)。

最后,您为新联系人构建 json 对象的方式没有正确完成,因此我已相应地对其进行了更正以添加适当的键值对。

function emailsasJSON() {
  
 var emailjson = {}
  var myContacts = ContactsApp.getContactGroup('System Group: My Contacts').getContacts();
  for (var i = 0; i < myContacts.length; i++) {
    var emails = myContacts[i].getEmails();
    var phonesobj = myContacts[i].getPhones();
    var phones = {}
    for (var j = 0; j < phonesobj.length; j++) {
       phones[phonesobj[j].getPhoneNumber().replace(/[_)(\s.-]/g,'')] = 1;
    }
    for (var j = 0; j < emails.length; j++) {
      emailjson[emails[j].getAddress().toLowerCase()] = {id: myContacts[i].getId(), phones:  phones};
      
    }
  }
  emailjson = JSON.stringify(emailjson);
  emailjson = JSON.parse(emailjson);
  return emailjson;
}

function addClient() {
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheetNew = ss.getActiveSheet(); 

 var clientsgroup = ContactsApp.getContactGroup('System Group: My Contacts')

//this is where we will insert the function from above to get the emailjson obj
 var emailjson = emailsasJSON()

 var contactarray = sheetNew.getDataRange().getValues();
 for (var i = 1 ; i < contactarray.length; i++){
   var name = contactarray[i][1]
   var email = contactarray[i][4]
   var phone = contactarray[i][3]
   
   
   
   if(emailjson[email.toLowerCase()]) { //check if email exists
     if(!emailjson[email.toLowerCase()]['phones'][phone.toString().replace(/[_)(\s.-]/g,'')]) { //if email exists but phone doesn't, add phone
     ContactsApp.getContactById(emailjson[email.toLowerCase()].id).addPhone(ContactsApp.Field.MOBILE_PHONE, phone)
     emailjson[email.toLowerCase()]['phones'][phone.toString().replace(/[_)(\s.-]/g,'')] = 1; //add it to the emailjson object in case there are more iterations of this contact in the sheet
     }
   } else { //add new contact if it doesn't exist
    var newcontact = ContactsApp.createContact(name.split(' ')[0],name.split(' ')[1], email);
     var newContactId = newcontact.getId();
     var phoneNumber = phone.toString().replace(/[_)(\s.-]/g,'');
     ContactsApp.getContactById(newContactId).addPhone(ContactsApp.Field.MOBILE_PHONE, phone);
     emailjson[email.toLowerCase()] = {id:newContactId,phones:{phoneNumber : 1}}
     clientsgroup.addContact(newcontact)
     }
  }
}

参考

【讨论】:

  • 快速搁置:无需添加“希望有帮助”信息,或询问读者是否不理解或需要其他内容。读者应该知道这一点。简洁和技术性写作是首选。 (编辑通常会删除此内容,您的帖子历史记录中有 146 个!)
  • 嗨@halfer!简洁和良好的回答质量并不是这个社区唯一的重要特征。礼貌和人际交往同样重要。此外,我认为大量提出问题的人缺乏经验或对社区不熟悉,你不能假设他们知道什么。我邀请您也从另一个角度查看信息,从 146 个带有此文本的答案中,没有编辑器删除它们。不过,谢谢你的建议,我会考虑的,如果你需要什么,请告诉我:D
  • 编辑们有大量的志愿工作要做,所以是的,很可能多年的闲聊材料或邀请评论对话的材料都逃脱了编辑。我们没有足够的编辑来完成we discuss on Meta Stack Overflow 那种技术写作。
  • 帮助中心给出了保持简洁的建议,所以我认为我们认为读者应该知道这一点是合理的。然而,这里有经验的贡献者知道,人们在深入研究之前不会阅读帮助材料,而且老手通常会主张人们在看到不符合任何最低准则的贡献后重新阅读 How to Ask .
  • 至于礼貌的角度:我已经在 cmets 中重播了数百次对话(以及已建立的社区对此的看法),大致是这样的。在现实生活中要有礼貌,这里的投稿人赞成礼貌,我们仍然主张简洁和技术写作。这里的答案有点像维基百科的文章——作者无疑是好人,但他们不会将问候放在顶部或将感谢阅读放在底部。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-09
  • 1970-01-01
  • 1970-01-01
  • 2017-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多