'Google Apps Script phone numbers from AD
I’m trying to create a script in Google Apps Script that gets users' phone numbers from AD and copies them into Google Sheets.
try {
if(user.phones[0].type = 'home'){
prop.push(user.phones[0].value);
}
if (user.phones[1].type = 'mobile'){
prop.push(user.phones[1].value );
}
if(user.phones[2].type = 'work'){
prop.push(user.phones[2].value);
}
else{
prop.push('');
}
}
catch(err){
prop.push('');
}
Now that does work, but it puts numbers in unwanted cell order. It seems to type: ‘work’ ‘home’ ‘mobile’. Also, if the user does not have 3 of those numbers, so f.e. Only ‘mobile’, this script puts it first where ‘work’ should be. I was hoping this code would put them in a specific cell order: ‘home’, ‘mobile’, ‘work’. Any ideas?
Solution 1:[1]
- Instead of
=use=== - The first two
ifhasn't andelse. If you don't want misplaced data, then you should addelse{ prop.push(''); }after each of them. - Regarding the order, you might have to create an Array of empty strings and replace the one that corresponds to each phone type by the corresponding value.
The following example uses Array.prototype.forEach and switch instead of several if
const prop = new Array(4).fill('');
user.phones.forEach(phone => {
switch(phone.type){
case 'home':
prop[0] = phone.value;
break;
case 'work':
prop[1] = phone.value;
break;
case 'mobile':
prop[2] = phone.value;
break;
default: // This will manage other phone types
prop[3] = prop[3].length === 0 ? phone.value : [prop[3], phone.value].join(',');
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
