Trouble updating contact phone numbers

What I’m trying to do is find all phone numbers in my contact which don’t already have a country code, then add the country code to them. In the console log, the county code seems to be added, but in reality not.

I’ve been scratching my head what I’ve done wrong or missed for days. Hopefully somebody here with a keen eye can help spot the problem.

Thank you in advance!

let containers = await ContactsContainer.all()
let contacts = await Contact.all(containers)

contacts.forEach((contact) => {
  let hknum = /^(\d{4}) ?(\d{4})$/i
  let nz = (contact.givenName ? contact.givenName : contact.organizationName)
  contact.phoneNumbers.forEach((phoneNumber) => {
    if (hknum.test(phoneNumber.value)) {
      phoneNumber.value = phoneNumber.value.replace(hknum, '+852 $1 $2')
      console.log(`${nz}: ${phoneNumber.value}`)
    }
  })
  Contact.update(contact)
})

Contact.persistChanges()

Hi,

This is a known issue (actually limitation) with the current implementation of the Contacts API. You should set the entire array when updating the phone numbers. E.g.

contact.phoneNumbers = [{
  "value": "+852 000 111 222"
}]

Thanks! With a little tweaking I got it to do the update that I need. The “label” and “localizedLabel” fields need to be preserved, otherwise if only the “value” is kept every number turns to “phone” only.

Here’s the final code in case anyone’s interested.

const countryLess = /^(\d{4}) ?(\d{4})$/i
const countryCoded = '+852 $1 $2'

let containers = await ContactsContainer.all()
let contacts = await Contact.all(containers)

function updatePhoneNumbers(contact) {
  let numbers = [],
      modified = false,
      number, z
  let name = (contact.givenName ? contact.givenName + ' ' + contact.familyName : contact.organizationName),
      nums = []

  for (z of contact.phoneNumbers) {
    number = z
    if (countryLess.test(z.value)) {
      number.value = z.value.replace(countryLess, countryCoded)
      modified = true
    } else {
      number.value = z.value
    }
    nums.push(number.value)
    numbers.push(number)
  }
  
  if (modified) {
    console.log(`${name.trim()}: ${nums.join(', ')}`)
    contact.phoneNumbers = numbers
    Contact.update(contact)
  }
}

contacts.forEach(updatePhoneNumbers)

Contact.persistChanges()
1 Like