Optimizing the IF condition - javascript

AddPatient = {};
if(GenderValue === undefined) {
AddPatient.Gender = ' ';
} else {
AddPatient.Gender = GenderValue;
}
if(DateOfBirthValue === undefined) {
AddPatient.DateOfBirth = ' ';
} else {
AddPatient.DateOfBirth = DateOfBirthValue;
}
if(SSNValue === undefined) {
AddPatient.SSN = ' ';
} else {
AddPatient.SSN = SSNValue;
}
if(RaceValue === undefined) {
AddPatient.Race = ' ';
} else {
AddPatient.Race = RaceValue;
}
if(ReligionValue === undefined) {
AddPatient.Religion = ' ';
} else {
AddPatient.Religion = ReligionValue;
}
if(CellPhoneValue === undefined) {
AddPatient.CellPhoneNumber1 = ' ';
} else {
AddPatient.CellPhoneNumber1 = CellPhoneValue;
}
if(HomePhoneValue === undefined) {
AddPatient.phonenumber1 = ' ';
} else {
AddPatient.phonenumber1 = HomePhoneValue;
}
if(PrimaryPhoneValue === undefined) {
AddPatient.PrimaryPhoneNumber = ' ';
} else {
AddPatient.PrimaryPhoneNumber = PrimaryPhoneValue;
}
if(EmailValue === undefined) {
AddPatient.EmailAddress1 = ' ';
} else {
AddPatient.EmailAddress1 = EmailValue;
}
AddPatient.ResidentialAddress = {};
if(AddressValue === undefined) {
AddPatient.AddressLine1 = ' ';
} else {
AddPatient.ResidentialAddress.AddressLine1 = AddressValue;
}
if(CityValue === undefined) {
AddPatient.City = ' ';
} else {
AddPatient.ResidentialAddress.City = CityValue;
}
if(StateValue === undefined) {
AddPatient.State = ' ';
} else {
AddPatient.ResidentialAddress.State = StateValue;
}
if(ZipValue === undefined) {
AddPatient.PostalCode = ' ';
} else {
AddPatient.ResidentialAddress.PostalCode = ZipValue;
}
Is there any better way to write the same code?

You can write
AddPatient.Gender = GenderValue || " ";
The || operator returns the left-most "truthy" operand, so this will evaluate to " " if GenderValue is "falsy" (such as undefined, false, "", 0, or null)

function isDefined(value){
if(value != null)
return value;
else
return ' ';
}
AddPatient = {};
AddPatient.Gender =isDefined(AddPatient);
and son on

Here is a suggestion to what you actually asked:
http://jsfiddle.net/mplungjan/b5yRw/
It will of course work with a form instead.
var GenderValue = "F";
var DateOfBirthValue; // undefined
var AddressValue = "some street";
// var CityValue; // undeclared
function addItem(obj,varName) {
obj[varName] = window.hasOwnProperty(varName+"Value")?window[varName+"Value"]||"not set":"not declared";
}
function addItemLoop(obj) {
for (var o in obj) {
if (typeof obj[o] === 'object') {
addItemLoop(obj[o]);
}
else {
addItem(obj, o);
}
}
}
AddPatient = {
Gender : " ",
DateOfBirth: " ",
ResidentialAddress : {
Address:" ",
City: " "
}
}
addItemLoop(AddPatient);
document.write("<br/>Gender (F):"+AddPatient.Gender);
document.write("<br/>DOB (not set):"+AddPatient.DateOfBirth);
document.write("<br/>ResidentialAddress Address (some street):"+AddPatient.ResidentialAddress.Address);
document.write("<br/>ResidentialAddress City (not declared):"+AddPatient.ResidentialAddress.City);
Previous answer
Not better but shorter using the ternary operator
AddPatient.Gender = (GenderValue === undefined)? " ":GenderValue;
or shortcut
AddPatient.Gender = GenderValue || " ";
Note - In the shortcut you WILL get a space if value is 0
In EITHER you will get an error if GenderValue has not been declared.
So somewhere you need a var GenderValue;
Example:
var b="hello", c;
var a = {}
a.x = b||"no b"
a.y = (c===undefined)? "no c here":c
a.z = c || "no c here either"
alert(a.x)
alert(a.y)
alert(a.z)

Here's one option:
function SetOrDefault(value, property) {
if (typeof(value) == 'undefined' || value == null) {
property = ' ';
}
else {
property = value;
}
}
And then call it like this:
SetOrDefault(GenderValue, AddPatient.Gender);

Related

File reader API gives no out put on AUDIO files

As a part of a before upload control, I check if added files actually match the filetype that their extension describes.
I do a filecheck using a hidden element. and if it fails, it gets removed after formdata append.
I check the files at the backend too, but I also want to check via File Reader process. All functions like createItems or readItems and so on, are working in all other cases, meaning that they return output of either null, true or false. While I get output from image and video files, audio files not at all. It should work.
The question is: Does the file reader read audio files differently compared to video and image files?
The following is only a tiny block of the actual code.
Now the question is: Why it doesn't return output on audio files?.
quest0 & quest1 are UI elements. Which is the element that I pull the files from.
reader is "new FileReader".
what.filecount is added while page init as readonly property.
readItems gives output on all kind off files,
However the UI html doesn't get updated if it is the file type is audio/?
for (var oD = 0; oD < what.files.length; oD++)
{
var pL = false;
if (typeof window.dofile === 'undefined' || !window.dofile) { return; }
if (file_s.exec(file) && !what.multiple) { pL = true; }
else
{
if (what.files.length > what.filecount)
{
alert('too many files added. only ' + what.filecount + ' are allowed.');
what.value = '';
if (quest0 != null)
{ quest0.innerHTML = ('too many files added. only ' + what.filecount + ' are allowed.'); }
return;
}
pL = true;
if ( !lastform.includes(what.form.id) ) { pL = false; }
}
if (what.files && what.files[oD] && pL == true)
{
if (file_prev != null)
{
if (file_prev.getAttribute('data-src') == '')
{file_prev.setAttribute('data-src', file_prev.src); }
file_prev.src = file_backsrc;
}
reader.onload = function(e)
{
init();
if (typeof file_prev === 'undefined')
{
if (quest1 != null) { quest1.innerHTML = 'Error occoured'; }
return;
}
if (file_p == 'img' || file_p == 'video' || file_p == 'audio')
{ file_prev.src = e.target.result; }
if (file_p == 'canvas') { /*not yet*/ }
kill.classList.remove('invisible');
if (quest1 != null) { quest1.innerHTML = 'file done'; }
}
reader.onerror = function(e)
{
e.preventDefault();
alert('There was an error with one of your file(s). Filename ' + what.files[oD].name + '');
what.value = '';
}
function waitfor(arr)
{
if (arr == null || arr.length == 0) { return; }
var aL = arr.length,
aL0 = arr.shift();
file_prev = _(aL0.file_prev);
lastfile = aL0.lastfile;
file_p = aL0.file_p;
reader.readAsDataURL(aL0.file);
aL0.kill.classList.add('invisible');
setTimeout(() => {
init();
waitfor(arr)
}, 1250);
if (quest1 != null)
{ quest1.innerHTML = 'processing ' + file_p; }
}
if (what.multiple)
{
var oA = 0;
lastfile = what.files[oD].name;
for (oA; oA < dK.children.length; oA++)
{
var oB = what.files[oD], oB0, oB1;
if (oB.type.includes('im')) { file_p = 'img'; }
if (oB.type.includes('au')) { file_p = 'audio'; }
if (oB.type.includes('vi')) { file_p = 'video'; }
if (lastfile != what.files[oD].name || lastfilearr.length <= what.filecount)
{
oB0 = dK.children[oA];
if (oB0.nodeName.toLowerCase() == file_p && what.form.querySelectorAll(file_p)[oD] != null)
{
if ( /*oB0.getAttribute('data-src')==''&&*/ !lastfilearr.includes(what.files[oD].name))
{
oB0 = what.form.querySelectorAll(file_p)[oD];
file_prev = oB0;
lastfilearr.push(what.files[oD].name);
oB0.setAttribute('data-src', lastfile);
oB1 = new Object({
'file_prev': file_prev.id,
'file_p': file_p,
'file': what.files[oD],
'kill': kill
});
stoargearr.push(oB1);
createtoast(['Filechecker', 'the ' + what.files[oD].name + ' is getting checked.', 3e3, true, true, ['bg-info', 'text-dark', 'rounded', 'px-2', 'mx-1']]);
createItems('upload', 's', what.files[oD].name, 'name:' + what.files[oD].name + ';nr:' + oD + ';filesize:' + what.files[oD].size + ';filesizehuman:' + Math.abs(what.files[oD].size / 1024 / 1024).toFixed(2) + ';lastmodified:' + new Date(what.files[oD].lastModified).toUTCString() + ';type:' + what.files[oD].type + ';');
}
}
}
}
if (stoargearr.length == what.files.length) { waitfor(stoargearr); }
else { reader.readAsDataURL(what.files[oD]); }
}
}
}
Does the "File reader API" react different on audio files as it does on video or image files?
Thanks for any help.
here it goes.
for (var oD = 0; oD < what.files.length; oD++) {
var pL = false;
if (typeof window.dofile === 'undefined' || !window.dofile) {
return;
};
if (file_s.exec(file) && !what.multiple) {
pL = true;
} else {
if (what.files.length > what.filecount) {
alert('too many files added. only ' + what.filecount + ' are allowed.');
what.value = '';
if (quest0 != null) {
quest0.innerHTML = 'too many files added. only ' + what.filecount + ' are allowed.';
};
return;
};
pL = true;
if (!lastform.includes(what.form.id)) {
pL = false;
};
};
if (what.files && what.files[oD] && pL == true) {
if (file_prev != null) {
if (file_prev.getAttribute('data-src') == '') {
file_prev.setAttribute('data-src', file_prev.src);
};
file_prev.src = file_backsrc;
};
reader.onload = function(e) {
init();
if (typeof file_prev === 'undefined') {
if (quest1 != null) {
quest1.innerHTML = 'Error occoured';
};
return;
};
if (file_p == 'img' || file_p == 'video' || file_p == 'audio') {
file_prev.src = e.target.result;
};
if (file_p == 'canvas') { /*not yet*/ };
kill.classList.remove('invisible');
if (quest1 != null) {
quest1.innerHTML = 'file done';
};
};
reader.onerror = function(e) {
e.preventDefault();
alert('There was an error with one of your file(s). Filename ' + what.files[oD].name + '');
what.value = '';
};
function waitfor(arr) {
if (arr == null || arr.length == 0) {
return;
};
var aL = arr.length,
aL0 = arr.shift();
file_prev = _(aL0.file_prev);
lastfile = aL0.lastfile;
file_p = aL0.file_p;
reader.readAsDataURL(aL0.file);
aL0.kill.classList.add('invisible');
setTimeout(() => {
init();
waitfor(arr)
}, 1250);
if (quest1 != null) {
quest1.innerHTML = 'processing ' + file_p;
};
};
if (what.multiple) {
var oA = 0;
lastfile = what.files[oD].name;
for (oA; oA < dK.children.length; oA++) {
var oB = what.files[oD],
oB0, oB1;
if (oB.type.includes('im')) {
file_p = 'img';
};
if (oB.type.includes('au')) {
file_p = 'audio';
};
if (oB.type.includes('vi')) {
file_p = 'video';
};
if (lastfile != what.files[oD].name || lastfilearr.length <= what.filecount) {
oB0 = dK.children[oA];
if (oB0.nodeName.toLowerCase() == file_p && what.form.querySelectorAll(file_p)[oD] != null) {
if ( /*oB0.getAttribute('data-src')==''&&*/ !lastfilearr.includes(what.files[oD].name)) {
oB0 = what.form.querySelectorAll(file_p)[oD];
file_prev = oB0;
lastfilearr.push(what.files[oD].name);
oB0.setAttribute('data-src', lastfile);
oB1 = new Object({
'file_prev': file_prev.id,
'file_p': file_p,
'file': what.files[oD],
'kill': kill
});
stoargearr.push(oB1);
createtoast(['Filechecker', 'the ' + what.files[oD].name + ' is getting checked.', 3e3, true, true, ['bg-info', 'text-dark', 'rounded', 'px-2', 'mx-1']]);
createItems('upload', 's', what.files[oD].name, 'name:' + what.files[oD].name + ';nr:' + oD + ';filesize:' + what.files[oD].size + ';filesizehuman:' + Math.abs(what.files[oD].size / 1024 / 1024).toFixed(2) + ';lastmodified:' + new Date(what.files[oD].lastModified).toUTCString() + ';type:' + what.files[oD].type + ';');
};
};
};
};
if (stoargearr.length == what.files.length) {
waitfor(stoargearr);
};
} else {
reader.readAsDataURL(what.files[oD]);
};
};
};```
if (quest1 != null) {
quest1.innerHTML = 'processing ' + file_p;
};
This block gives no output on audio files.

convert a string containing boolean values to a boolean

If I have this ;
var a = "(true && false) && true && false"
And if I want to evaluate this string , what are the options ?
If I say, this code will be generated in the browser but there will be absolutely no user input in it , would it be safe to use eval ?
If not, what is the most performant way of parsing it ?
EDIt :
By the way, the string is dynamic , so I can't gaurantee that it's always like above , so it could be :
var a = "(true && false) || (true && (true && false)) && true && false"
FIY :
I know I can use eval, all I'm asking is, why I shouldn't use eval, or is there any other options?
EDIT : the original problem :
var a = function(){ return false} // all of them always return a boolean
var b = function(){ return true}
var c = function(){ return true}
var d = function(){ return false}
var conditions = "(a && b) && c && d"
I can't change the above code , I need to parse it, I need the condition to be evaluated ;
function ExecuteJavascriptString() {
var n = 0;
var s = "(true || false) || (true || (true || false)) && true";
var ifstate = " if (" + s + ") { console.log('done'); } ";
setTimeout(ifstate, 1);
}
ExecuteJavascriptString()
I was thinking maybe you can atleast verify that the string contains what you think it should contain, before running eval on it, using the RegExp /(?:(?:true)|(?:false)|(?:&&)|(?:\|\|)|[()\s])/g:
var validExp = "(true && false && true) || (true && (true && false)) && true";
var evilExp = "(true && false && true) || (true && (true && false)) && true function() { console.log('do evil stuff'); }";
console.log(evalBoolStr(validExp)); //false
console.log(evalBoolStr(evilExp)); //Invalid input
function evalBoolStr(str) {
if(str.match(/(?:(?:true)|(?:false)|(?:&&)|(?:\|\|)|[()\s])/g).join('') === str) {
return eval(str);
}
return 'Invalid input';
}
An attempt at actually writing a parser for boolean strings:
function parseBoolStr(str) {
var expressions = {};
var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)");
var expressionIndex = 0;
str = str.trim();
while (str.match(expressionRegex)) {
var match = str.match(expressionRegex)[0];
var expression = 'boolExpr' + expressionIndex;
str = str.replace(match, expression);
match = match.replace('(', '').replace(')', '');
expressions[expression] = match;
expressionIndex++;
}
return evalBoolStr(str, expressions);
}
function evalBoolStr(str, expressions) {
var conditions = str.split(' ');
if (conditions.length > 0) {
var validity = toBoolean(conditions[0], expressions);
for (var i = 1; i + 1 < conditions.length; i += 2) {
var comparer = conditions[i];
var value = toBoolean(conditions[i + 1], expressions);
switch (comparer) {
case '&&':
validity = validity && value;
break;
case '||':
validity = validity || value;
break;
}
}
return validity;
}
return 'Invalid input';
}
function toBoolean(str, expressions) {
var inversed = 0;
while (str.indexOf('!') === 0) {
str = str.replace('!', '');
inversed++;
}
var validity;
if (str.indexOf('boolExpr') === 0) {
validity = evalBoolStr(expressions[str], expressions);
} else if (str == 'true' || str == 'false') {
validity = str == 'true';
} else {
validity = window[str]();
}
for (var i = 0; i < inversed; i++) {
validity = !validity;
}
return validity;
}
var exp1 = "(true && true || false) && (true || (false && true))";
var exp2 = "(true && false) && true && false";
var exp3 = "(true && !false) && true && !false";
var exp4 = "(a && b) && c && d";
console.log(exp1 + ' = ' + parseBoolStr(exp1));
console.log(exp2 + ' = ' + parseBoolStr(exp2));
console.log(exp3 + ' = ' + parseBoolStr(exp3));
console.log(exp4 + ' = ' + parseBoolStr(exp4));
function parseBoolStr(str) {
var expressions = {};
var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)");
var expressionIndex = 0;
str = str.trim();
while (str.match(expressionRegex)) {
var match = str.match(expressionRegex)[0];
var expression = 'boolExpr' + expressionIndex;
str = str.replace(match, expression);
match = match.replace('(', '').replace(')', '');
expressions[expression] = match;
expressionIndex++;
}
return evalBoolStr(str, expressions);
}
function evalBoolStr(str, expressions) {
var conditions = str.split(' ');
if (conditions.length > 0) {
var validity = toBoolean(conditions[0], expressions);
for (var i = 1; i + 1 < conditions.length; i += 2) {
var comparer = conditions[i];
var value = toBoolean(conditions[i + 1], expressions);
switch (comparer) {
case '&&':
validity = validity && value;
break;
case '||':
validity = validity || value;
break;
}
}
return validity;
}
return 'Invalid input';
}
function toBoolean(str, expressions) {
var inversed = 0;
while (str.indexOf('!') === 0) {
str = str.replace('!', '');
inversed++;
}
var validity;
if (str.indexOf('boolExpr') === 0) {
validity = evalBoolStr(expressions[str], expressions);
} else if (str == 'true' || str == 'false') {
validity = str == 'true';
} else {
validity = window[str]();
}
for (var i = 0; i < inversed; i++) {
validity = !validity;
}
return validity;
}
function a() {
return false;
}
function b() {
return true;
}
function c() {
return true;
}
function d() {
return false;
}
Usage would then simply be parseBoolStr('true && false'); //false

Javascript code broken

This is my first attempt at a little more complex code structure. The thing is my IDE says it technically works , jsfiddle says it doesn't, it actually initializes only the two confirm functions that I declared "confirmUserName();" and "confirmFullName();"
Can someone explain why i did such a horrible job.
var userList = [];
var username = "";
var fullname = "";
var addUserName = addUser(username, userList); v
var addFullName = addUser(fullname, userList);
function addUser(usrName, list) {
if(list.length == 0) {
list.push(usrName); // userlist empty add the new user
} else {
for (var i = 0; i < list.length; i++) {
if(list[i] == undefined) {
list[i] = usrName;
return list;
} else if(i == list.length - 1) {
list.push(usrName);
return list;
}
}
}
} // Function that adds user and name to list
var usernameQuery;
function confirmUserName() {
confirm("Is " + username + " your first choice?");
if (confirmUserName == true) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
var fullnameQuery; /
function fullnameConfirm() {
confirm("Is " + fullname + " your first choice ");
if (fullnameConfirm == true) {
return startRide;
} else {
return fullnameQuery;
}
}
if(username == undefined) {
usernameQuery = function() {
username = prompt("You are the first user to play, \n" +
" Chose and let the game begin !");
return addUserName;
};
} else {
usernameQuery = function() {
username = prompt("What username whould you like to have ? \n" +
" Chose and let the game begin !");
return addUserName;
};
}
confirmUserName();
if(fullname == undefined) {
fullnameQuery = function() {
fullname = prompt("Enter your real name !");
return addFullName;
};
} else {
fullnameQuery = function() {
fullname = prompt("Enter your real name!");
return addFullName;
};
}
fullnameConfirm();
There is a lot wrong with the code you posted -- I'll just take one chunk:
function confirmUserName() {
// The return value of `confirm` is ignored.
confirm("Is " + username + " your first choice?");
// confirmUserName is the name of your function.
// You sould be using `===` instead of `==`
// Or, not comparing against true at all.
if (confirmUserName == true) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
Fixed function:
function confirmUserName() {
var res = confirm("Is " + username + " your first choice?");
if (res) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
It does not throw Errors with this, but I dont know in which situation you want your code to be implemented and what it should do, I hope this is what you need:
var userList = [];
var username = "";
var fullname = "";
var addUserName = addUser(username, userList);
var addFullName = addUser(fullname, userList);
function addUser(usrName, list) {
if (list.length === 0) {
list.push(usrName); // userlist empty add the new user
} else {
for (var i = 0; i < list.length; i++) {
if (list[i] === undefined) {
list[i] = usrName;
return list;
} else if (i == list.length - 1) {
list.push(usrName);
return list;
}
}
}
} // Function that adds user and name to list
var usernameQuery;
function confirmUserName() {
confirm("Is " + username + " your first choice?");
if (confirmUserName === true) {
return fullnameQuery;
} else {
return usernameQuery;
}
}
var fullnameQuery;
function fullnameConfirm() {
confirm("Is " + fullname + " your first choice ");
if (fullnameConfirm === true) {
return startRide;
} else {
return fullnameQuery;
}
}
if (username === undefined) {
usernameQuery = function () {
username = prompt("You are the first user to play, \n" +
" Chose and let the game begin !");
return addUserName;
};
} else {
usernameQuery = function () {
username = prompt("What username whould you like to have ? \n" +
" Chose and let the game begin !");
return addUserName;
};
}
confirmUserName();
if (fullname === undefined) {
fullnameQuery = function () {
fullname = prompt("Enter your real name !");
return addFullName;
};
} else {
fullnameQuery = function () {
fullname = prompt("Enter your real name!");
return addFullName;
};
}
fullnameConfirm();

Where does this unspecified error comes from?

I'm trying to format any kind of variables to achieve some kind of toString() method.
It's working for pretty complex objects and arrays, handling circular references, but when I try to call it on a jQuery object: format($("body")), for testing it on large complex objects, I got this error:
Unhandled exception at line 330, column 21 in ms-appx://8b94d51c-586e-4f3f-bb9c-fa75d62508cd/js/default.js
0x80004005 - Erreur d’exécution JavaScript: Erreur non spécifiée.
0x80004005 - JavaScript Run-time Error: Unspecified error. // I translated it for you
Here is my code (with a // ERROR! comment next to the line 330):
function format(arg, parents, indent) {
var maxParent = 25;
if (parents === undefined) {
parents = [];
}
if (indent === undefined) {
indent = 1;
}
if (contains(parents, arg)) {
return '<span class="brackets">[Circular]</span>';
}
if (typeof arg === 'string' && parents.length > 0) {
return '"' + htmlEntities(arg) + '"';
} else if (Array.isArray(arg)) {
parents.push(arg);
if (parents.length >= maxParent) {
return '<span class="brackets">[Array]</span>';
}
var ret = "[ ";
for (var i = 0, len = arg.length; i < len; i++) {
if (i !== 0) {
ret += ", ";
}
ret += "<br>";
ret += addIndent(indent);
ret += format(arg[i], parents, indent + 1);
}
ret += "<br>";
ret += addIndent(indent - 1);
ret += " ]";
return ret;
} else if (arg === null) {
return '<span class="void">null</span>';
} else if (arg === void 0) {
return '<span class="void">undefined</span>';
} else if (typeof arg === 'number' && (isNaN(arg) || !isFinite(arg))) {
return '<span class="void">' + arg.toString() + '</span>';
} else if (typeof arg === 'object' && arg !== null) {
if (parents.length >= maxParent) {
return '<span class="brackets">[Object]</span>';
} else {
parents.push(arg);
}
var ret = "{";
var first = true;
for (var key in arg) {
if (!first) {
ret += ", ";
}
else {
first = false;
}
ret += "<br>";
ret += addIndent(indent);
ret += key;
ret += ": ";
if (typeof arg[key] === 'function') {
ret += '<span class="brackets">[Function]</span>';
} else {
ret += format(arg[key], parents, indent + 1); // ERROR!
}
}
ret += "<br>";
ret += addIndent(indent - 1);
ret += "}";
remove(parents, arg);
return ret;
}
return arg;
}
Do you have any ideas why this error is occuring?
What can I do to fix it?
Out of the top of my head I can think that arg[key] is null by the time you call the format function. Synchronize the if statement so it executes only after arg[key] is not null.

How to import data of gmail contacts, using javascript Google Contact API, in more detailed format?

I'm using code from this page http://code.google.com/apis/contacts/docs/1.0/developers_guide_js.html to get list of gmail contacts. Actually it works ok, but I get data of name, address, etc like a simple string, with "\n" as separator, for example:
<script type="text/javascript">
var contactsService;
var scope = 'https://www.google.com/m8/feeds';
function setupContactsService() {
//contactsService = new google.gdata.contacts.ContactsService('exampleCo-exampleApp-1.0');
contactsService = new google.gdata.contacts.ContactsService('GoogleInc-jsguide-1.0');
}
function getMyContacts() {
var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full'; //?max-results=9999&alt=json&v=3.0
var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
setupContactsService();
contactsService.getContactFeed(query, handleContactsFeed, handleError);
}
var handleContactsFeed = function(result) {
var entries = result.feed.entry;
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var addrs = entry.getPostalAddresses();
var name = entry.getTitle();
// logging
console.log(addrs[0]);
console.log(name);
}
}
function handleError(e) {
alert(e.cause ? e.cause.statusText : e.message);
}
</script>
it gives me an object where name and address values are simple strings.
Can I get somehow data in like associative array format, where address will contains separate values of street, zip, city, country; and name separate values of first name, last name etc.
Like:
{
"type": "address",
"value":
{
"street": "Starret 1234",
"city": "City name",
"stateOrProvince": "ca",
"postalCode": "73000",
"country": "USA"
}
},
{
"type": "name",
"value":
{
"firstName": "Allen",
"lastName" : "Iverson",
.....
}
}
Thanks in advance!
Seems I found an answer, for get more detailed and formatted info need to add additional parameter to contactsFeedUri for google.gdata.contacts.ContactQuery.
This additional parameter is: ?v=3.0
So in my case function will looks like:
function getMyContacts() {
var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full?v=3.0&alt=json';
var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
setupContactsService();
contactsService.getContactFeed(query, handleContactsFeed, handleError);
}
And for get necessary data I create a simple obj, which can be useful for somebody:
function contactEntry(entry) {
this.entry = entry;
this.testEntry = function() {
alert( 'test entry' )
};
this.getFirstName = function() {
if ((entry.gd$name == null) || (entry.gd$name.gd$givenName == null) || (entry.gd$name.gd$givenName.$t == null)) {
return '';
} else {
return entry.gd$name.gd$givenName.$t;
}
};
this.getLastName = function() {
if ((entry.gd$name == null) || (entry.gd$name.gd$familyName == null) || (entry.gd$name.gd$familyName.$t == null)) {
return '';
} else {
return entry.gd$name.gd$familyName.$t;
}
};
this.getAdditionalName = function() {
if ((entry.gd$name == null) || (entry.gd$name.gd$AdditionalName == null) || (entry.gd$name.gd$AdditionalName.$t == null)) {
return '';
} else {
return entry.gd$name.gd$familyName.$t;
}
};
this.getEmail = function() {
if ((entry.gd$email == null) || (entry.gd$email.length == 0) || (entry.gd$email[0].address == null)) {
return '';
} else {
return entry.gd$email[0].address;
}
};
this.getStreet = function() {
if (!this._addrExists() || (entry.gd$structuredPostalAddress[0].gd$street == null)) {
return '';
} else {
return entry.gd$structuredPostalAddress[0].gd$street.$t;
}
};
this.getCity = function() {
if (!this._addrExists() || (entry.gd$structuredPostalAddress[0].gd$city == null)) {
return '';
} else {
return entry.gd$structuredPostalAddress[0].gd$city.$t;
}
};
this.getCountry = function() {
if (!this._addrExists() || (entry.gd$structuredPostalAddress[0].gd$country == null)) {
return '';
} else {
return entry.gd$structuredPostalAddress[0].gd$country.$t;
}
};
this.getPostcode = function() {
if (!this._addrExists() || (entry.gd$structuredPostalAddress[0].gd$postcode == null)) {
return '';
} else {
return entry.gd$structuredPostalAddress[0].gd$postcode.$t;
}
};
this.getPhone = function() {
if ((entry.gd$phoneNumber == null) || (entry.gd$phoneNumber.length == 0) || (entry.gd$phoneNumber[0].$t == null)) {
return '';
} else {
return entry.gd$phoneNumber[0].$t
}
};
this.getOrganization = function() {
if ((entry.gd$organization == null) || (entry.gd$organization.length == 0) || (entry.gd$organization[0].getOrgName() == null)) {
return '';
} else {
return entry.gd$organization[0].getOrgName().getValue();
}
};
this.getBirthday = function() {
if ((entry.gContact$birthday == null) || (entry.gContact$birthday.when == null)) {
return '';
} else {
return entry.gContact$birthday.when;
}
};
this.getEvent = function() {
if ((entry.gContact$event == null) || (entry.gContact$event.length == 0) || (entry.gContact$event[0].gd$when == null)) {
return '';
} else {
return entry.gContact$event[0].gd$when.startTime;
}
};
// protected methods
this._addrExists = function() {
if ((entry.gd$structuredPostalAddress == null) || (entry.gd$structuredPostalAddress.length == 0)) {
return false;
}
return true;
};
}
It can be used in this way:
var handleContactsFeed = function(result) {
var entries = result.feed.entry;
var contact = new contactEntry(entries[0]);
var address = {};
address['fname'] = contact.getFirstName();
address['lname'] = contact.getLastName() + (contact.getAdditionalName() != '' ? ' ' + contact.getAdditionalName() : '');
address['address'] = contact.getStreet();
address['city'] = contact.getCity();
address['country'] = contact.getCountry();
address['zip'] = contact.getPostcode();
address['phone'] = contact.getPhone();
address['mail'] = contact.getEmail();
address['organization'] = contact.getOrganization();
address['birthday'] = contact.getBirthday();
address['event'] = contact.getEvent();
}

Categories

Resources