push multivalue elements to array in titanium (JS) - javascript

In titanium im accessing the phone book and i have an array with contact information (single and multi-value fields). i have troubles with the multi-value emails field. the multi-value fields stringified objects looks like this (work, home, other as well as multiple emails for work, home, etc):
email: {"work":["kate-bell#mac.com","www.icloud.com"]}
phone: {"work":["(555) 766-4823"],"other":["(707) 555-1854"]}
the code i have so far:
function buddy_check(){
var all_emails= []; // array of emails from senders contacts
var multiValue = ['email'];
var people = Ti.Contacts.getAllPeople(); // gets all contacts (recordId, name,…)
for (var i=0, ilen=people.length; i<ilen; i++){
Ti.API.info('---------------------');
var person = people[i];
//for (var j=0, jlen=singleValue.length; j<jlen; j++){
// Ti.API.info(singleValue[j] + ': ' + person[singleValue[j]]);
// }
for (var j=0, jlen=multiValue.length; j<jlen; j++){
Ti.API.info(multiValue[j] + ': ' + JSON.stringify(person[multiValue[j]]));
all_emails.push();
}
}
i need all emails of the phone book in one array, separated by comma. underscore functions would work as well.
what do i have to push to the all_emails array? is there a simpler way to extract the emails and put it in an array (e.g search for "#")?
thx for sharing insights!
P.S: the user is of course informed that the emails are being checked with our database.

from here: http://www.oodlestechnologies.com/blogs/How-to-extract-contact-list-having-phone-numbers-and-emails-from-iPhone-contacts-using-Titanium
var data = [];
var people = Ti.Contacts.getAllPeople();
for (var i = 0,
ilen = people.length; i < ilen; i++) {
var person = people[i];
var title = people[i].fullName;
if (!title || title.length === 0) {
title = "No Name";
}
Ti.API.info("person name : " + title);
var personEmails = [];
//this check is used for conforming that array will contain at least one email that is actual.
var actualConfirmed = false;
//fetching emails
//Ti.API.info("person email::::1 " + JSON.stringify(person.email));
for (var temp in person.email) {
var temp_emails = person.email[temp];
if (temp_emails && (temp_emails.length > 0)) {
//Ti.API.info("person email::::2 " + JSON.stringify(temp_emails));
for (var k = 0; k < temp_emails.length; k++) {
var temp_email = temp_emails[k];
var isActualEmail = emailValidation(temp_email);
Ti.API.info("temp_email " + temp_email + " :::: isActualEmail " + isActualEmail);
if (isActualEmail) {
actualConfirmed = true;
personEmails.push(temp_email);
}
}
}
}
- See more at: http://www.oodlestechnologies.com/blogs/How-to-extract-contact-list-having-phone-numbers-and-emails-from-iPhone-contacts-using-Titanium#sthash.q7TJF8Lg.dpuf

Related

Google Forms Appscript - Skip blank responses and keep adding questions and responses

Totally new to javascript, but I'm able to hack together existing pieces. I'm a bit stuck now.
I have a script that joins together a bunch of Q + As from a Google Form.
A lot of the questions are optional, but I'm not sure how to skip those lines, so it still prints the questions and line breaks.
var form = FormApp.getActiveForm();
var formResponses = form.getResponses();
var formResponse = formResponses[formResponses.length-1];
var itemResponses = formResponse.getItemResponses();
// ---------
// create the notes portion of the form
var notes = "XYZ Submission \n\n";
for (var j = 0; j < itemResponses.length; j++) {
var itemResponse = itemResponses[j];
// add each Q & A to the notes and then add 2 endlines if the response isn't blank
if (itemResponse.getResponse() != null) {
notes = notes + itemResponse.getItem().getTitle() + "\n" + itemResponse.getResponse() + "\n\n";
}
}
What am I doing wrong here?
The responses to the unanswered optional questions are not null; they are blank.
So try replacing this:
if (itemResponse.getResponse() != null) {
with this:
if (itemResponse.getResponse() != '') {
Ok I think I found the answer! I actually didn't find what kind of value is in the variable, but I arealized I could just check if it had a truthy value or not.
So this worked
var form = FormApp.getActiveForm();
var formResponses = form.getResponses();
var formResponse = formResponses[formResponses.length-1];
var itemResponses = formResponse.getItemResponses();
// ---------
// create the notes portion of the form
var notes = "XYZ Submission \n\n";
// cycle through all form responses and add them all to the notes variable
for (var j = 0; j < itemResponses.length; j++) {
var itemResponse = itemResponses[j];
if (itemResponse.getResponse()) {
console.log(itemResponse.getResponse());
notes = notes + itemResponse.getItem().getTitle() + "\n" + itemResponse.getResponse() + "\n\n";
}
}

search Gmail for xls attachments

with this code I use to save attachment to a shared google drive folder and got notified when a change happen to it by a mail. All is fine as long as I search for pdf attachments. As I set file:xls the messages returned are far more than expected. Not only, the threads returned by the debug are correct, as well as insert the query in the search filed in Gmail, but the getmessages() returned in this case 38 messages (and attachements! And not only xls but also a pdf) of the query parameters. The conversation view is disabled in Gmail, the only match with this attachments is the from: field.
I tried to change the reference data (by adding newer_than), and nothing changed; I changed the for cycle, and nothing changed. Am I missing something really stupid or is this a kind of bug with xls?
function salvataggioTavoloTecnico(){
var folderName = 'tavoloTecnico';
var p = 0;
var f1s= DriveApp.getFoldersByName(folderName).next().getFiles();
while (f1s.hasNext()) {
var f1 = f1s.next();
p++
} Logger.log(p);
var d = new Date();
d.setDate(d.getDate()-1);
var n = d.getFullYear() + "/" + addZero(d.getMonth()+1) + "/" + addZero(d.getDate());
var query = 'in:anywhere has:attachment filename:XLS newer_than:5d (from:mariano.casillo#mit.gov.it OR from:donato.castigliego#mit.gov.it OR from:luciano.aloia#mit.gov.it)';
//var query = 'in:anywhere has:attachment filename:xls '+ 'after:'+n+' (from:mariano.casillo#mit.gov.it OR from:donato.castigliego#mit.gov.it OR from:luciano.aloia#mit.gov.it)';
var elenco = GmailApp.search(query);
var quanteMail = elenco.length; Logger.log(quanteMail);
labelName = GmailApp.createLabel('Movimenti - Tavolo tecnico');
for (var i = 0 ; i < quanteMail; i++) {
//for ( var i in elenco) {
elenco[i].addLabel(labelName);
var thr = elenco[i];
var nn = thr.getMessageCount();
Logger.log(nn);
var mesgs = thr.getMessages();
var www = mesgs.length;
for(var j = 0 ; j < www ; j ++){
var attachments = mesgs[j].getAttachments();
var rrr = attachments.length;
for(var k = 0 ; k < rrr ; k ++) {
var attachment = attachments[k];
var attachmentBlob = attachment.copyBlob();
var file = DriveApp.createFile(attachmentBlob);
DriveApp.getFoldersByName(folderName).next().addFile(file);
}
}
}
var c = 0;
var f2s = DriveApp.getFoldersByName(folderName).next().getFiles();
while (f2s.hasNext()) {
var f2 = f2s.next();
c++
}
if ( c > p) { GmailApp.sendEmail("me#me.com", " avviso "+folderName, "Un nuovo file è stato aggiunto")};
}
I still don't know why the search by code return more messages out of the parameters, but I workaround it by search in the "wrong" messages only those I need by parse the date, like this, and now it works:
......
var threads = GmailApp.search(query);
for ( var i in threads) {
threads[i].addLabel(labelName);
var mesgs = threads[i].getMessages();
var www = mesgs.length;
for(var j = 0 ; j < www ; j ++){
if ( mesgs[j].getDate() < d ){} else {
var attachments = mesgs[j].getAttachments();
var rrr = attachments.length;
for(var k = 0 ; k < rrr ; k ++) {
var attachment = attachments[k];
var attachmentBlob = attachment.copyBlob();
var file = DriveApp.createFile(attachmentBlob);
DriveApp.getFoldersByName(folderName).next().addFile(file);
}
}
}
}
.......

Spliting String and getting appropriate value in JavaScript

I have a string where |||| means next to it is the directory. ||| means the user is allowed to access this directory and || means the files allocated to these users follow.
I need to find allocated file names of a specific user from this string. I have tried to split the string and assign values to an array but I am not able to get the result I'm looking for.
This is the string:
||||Root|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,||||1400842226669|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,||||1401191909489|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,LimitTest_20140528164643.xlsx,
And here is my attempt:
function getData() {
var user = 'km11285c';
var value = "||||Root|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,||||1400842226669|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,||||1401191909489|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,LimitTest_20140528164643.xlsx,";
var users = null;
var files = null;
var Dir = value.split("||||");
var arrayLength = Dir.length;
for (var i = 0; i < arrayLength; i++) {
users = Dir[i].split("|||");
}
return users;
}
console.log(getData());
and the jsFiddle
I changed your jsfiddle example a bit so maybe you need to change the code here and there, but something like this should work:
function buildTree(data) {
var tree = [];
var dirs = data.split("||||");
// Remove the first entry in the array, since it should be empty.
dirs.splice(0, 1);
for (var i = 0; i < dirs.length; ++i) {
var tempArray = dirs[i].split("|||");
var dirName = tempArray[0];
var usersAndFiles = tempArray[1];
tempArray = usersAndFiles.split("||");
var users = tempArray[0];
var files = tempArray[1];
var treeDir = { name: dirName };
treeDir.users = users.split(",");
treeDir.files = files.split(",");
tree.push(treeDir);
}
return tree;
}
function getData() {
var user = 'km11285c';
var value="||||Root|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,||||1400842226669|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,||||1401191909489|||adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,km11285c,km61052,km61639c,adil001,kl04707c,km47389,km58184,km61052,kq61023c,||LimitTest_20140528164643.xlsx,testTask2_20140528140033.xlsx,testTask1_20140528135944.xlsx,testTask2_20140528140033.xlsx,LimitTest_20140528164643.xlsx,";
var tree = buildTree(value);
for (var i = 0; i < tree.length; ++i) {
var dir = tree[i];
if (dir.users.indexOf(user) >= 0) {
console.log("User '" + user + "' has access to directory '" + dir.name + "', which contains these files: " + dir.files.join(","));
}
}
}
getData();

Script is working, but only with a "hack"

Background:
I am part of a large family and to save everyone some money at Christmas, we do a Secret Santa of sorts for gift giving. I am writing this script so that this all can be managed via a spreadsheet since our process can be somewhat messy. The rules are:
Each "Santa" is given two names that they must buy gifts for.
Those 2 names can not be the same.
Couples can not give gifts to each other or their children. Children
can not give gifts to their siblings or their parents.
Here is a table with some example data:
The Problem
I believe my issue is occurring because of the following code:
//Remove disallowedNames from currentAvailableNames
for (j=0; j<disallowed.length; j++){
var disallowedName = disallowed[j];
currentAvailableNames.splice(currentAvailableNames.indexOf(disallowed[j]), 1);
}
For some reason, the disallowed name(s) are also being removed from the availableNames array and I have no idea why. The only way I have been able to "fix" it, is by adding in the following code after the recipient has been picked:
//Add Disallowed Names back to Available Names Array
for (k=0; k<disallowed.length; k++){
var disallowedName = disallowed[k];
if (disallowedName.length >0) {
availableNames.push(disallowedName);
}
}
Original Code
function giftAssignments() {
//Get Settings
var ss = SpreadsheetApp.getActiveSpreadsheet();
var settings = ss.getSheetByName("Settings");
var resultsSheet = ss.getSheetByName("Results");
var numOfAssignments = settings.getRange("B2").getValue();
var minPrice = settings.getRange("B3").getValue();
var maxPrice = settings.getRange("B4").getValue();
var firstName = settings.getRange("B5").getValue();
var santasLastRow = settings.getLastRow();
var santasLastCol = settings.getLastColumn();
var santasTotal = santasLastRow - firstName + 1;
var santasAsRange = settings.getRange(firstName,1,(santasLastRow - firstName + 1), santasLastCol).getValues();
//Create Santas Array (santas)
var santas = []
for (var i=0; i<santasAsRange.length; i++) {
var name = santasAsRange[i][0];
var email = santasAsRange[i][1];
var disallowedAsString = santasAsRange[i][2];
disallowedAsString = disallowedAsString.replace(", ",",");
var disallowed = disallowedAsString.split(",");
disallowed.push(name);
var santa = [];
santa[0] = name;
santa[1] = email;
santa[2] = disallowed;
santas.push(santa);
}
//Create Array of Names (availableNames)
var availableNames = [];
for (i=0; i<santas.length; i++) {
var aName = santas[i][0];
availableNames.push(aName);
}
//Assign Recipients
var results = assignRecip(santas, availableNames);
Logger.log("RESULTS = " + results);
}
function assignRecip(santas, names) {
var availableNames = names;
for (i=0; i<santas.length; i++) {
var currentAvailableNames = availableNames;
var name = santas[i][0];
var disallowed = santas[i][2];
Logger.log("Santa = " + name);
Logger.log("availableNames = " + availableNames);
//Remove disallowedNames from currentAvailableNames
for (j=0; j<disallowed.length; j++){
var disallowedName = disallowed[j];
currentAvailableNames.splice(currentAvailableNames.indexOf(disallowed[j]), 1);
}
Logger.log("currentAvailableNames = " + currentAvailableNames);
//Pick Random Ricipient from currentAvailableNames
var recipient = currentAvailableNames[Math.floor(Math.random() * currentAvailableNames.length)];
Logger.log("Recipient = " + recipient);
//Add Recipient to Santa Array
santas[i].push(recipient);
//Add Disallowed Names back to Available Names Array
for (k=0; k<disallowed.length; k++){
var disallowedName = disallowed[k];
if (disallowedName.length >0) {
availableNames.push(disallowedName);
}
}
//Add Recipient to Disallowed Names Array
santas[i][2].push(recipient);
//Remove Recipient from Available Names Array
availableNames.splice(availableNames.indexOf(recipient),1);
Logger.log("availableNames = " + availableNames);
Logger.log(" ");
}
return santas;
}
They're references to the same Array. This code doesn't copy the Array itself. It copies the reference to the Array.
var currentAvailableNames = availableNames;
You can fix it using .slice().
var currentAvailableNames = availableNames.slice();
Now you have two separate Arrays, so direct modifications to currentAvailableNames will not affect availableNames.
Note that this is a shallow clone. If it was an Array of Objects or Arrays, then modifications to the nested Object would still be visible from both Arrays.

Why is a named function not working when the unnamed was?

I had this code:
$('#testsPane').live("click", function() {//if the secondary ui nav tests is
selected
//Displays the test list
var listOfTests = "";
var subjects = [];
var tests= [];
var titles = [];
var keysplit;
var testSubj;
var key, value;
for (var i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);
value = localStorage.getItem(key);
keysplit = key.split(".");
tests.push(value);
titles.push(keysplit[0]);
subjects.push(keysplit[keysplit.length-1]);
}
for(var i=0; i < tests.length; i++) {
listOfTests += '<div class="testDisplayBox"><div
class="subjColorBar"></div><div class="testListIndiContain"><span
class="testListTitle">' + titles[titles.length-(i+1)] + '</span><span> in
</span><span class="testListSubj">' + subjects[subjects.length-(i+1)] +
'</span></div><div class="testListTags"><span
class="specTags">quiz</span></div></div>';
}
var testsDashboard = '<div id="testsList">' + listOfTests + '</div>';
$('#selectedPane').append(testsDashboard);//adds the html to the pane to make it
into the tests dashboard
})
The above code worked but I wanted to reuse some of it so I put it into a function. When I did that it did not work. Any idea why? The code below is with using a named function.
function grabTestList() {//Displays the test list
var keysplit;
var testSubj;
var key, value;
for (var i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);
value = localStorage.getItem(key);
keysplit = key.split(".");
tests.push(value);
titles.push(keysplit[0]);
subjects.push(keysplit[keysplit.length-1]);
}}
$('#testsPane').live("click", function() {//if the secondary ui nav tests is selected
grabTestList();
var listOfTests = "";
var subjects = [];
var tests= [];
var titles = [];
for(var i=0; i < tests.length; i++) {
listOfTests += '<div class="testDisplayBox"><div class="subjColorBar"></div><div class="testListIndiContain"><span class="testListTitle">' + titles[titles.length-
(i+1)] + '</span><span> in </span><span class="testListSubj">' + subjects[subjects.length-(i+1)] + '</span></div><div class="testListTags"><span
class="specTags">quiz</span></div></div>';
}
var testsDashboard = '<div id="testsList">' + listOfTests + '</div>';
$('#selectedPane').append(testsDashboard);//adds the html to the pane to make it into the tests dashboard
})
Because you are defining variables in the context of the anonymous function which are unknown to the named function. Pass them to grabTestList so the .push methods can mutate those arrays.
function grabTestList(tests, titles, subjects) {
// manipulate tests/titles/subjects
}
$('blah').live('click', function() {
var tests = [], titles = [], subjects = [];
grabTestList( tests, titles, subjects );
// since tests, titles, and subjects are mutated by the function, you can just loop through them here.
})
DEMO:
Here's a sample version which you can base your code on: http://jsfiddle.net/JLK6N/2/
updated with the fix: http://jsfiddle.net/JLK6N/3/
Remember that objects are passed by reference, arrays are objects, and methods like .push are mutator methods.

Categories