javascript nested for loop from a string(multiple layers) - javascript

I have a string that I am trying to loop through. It has nested arrays and I want to get the values from each layer. However I seem to be getting an undefined from the second layer onwards.
//String [{"username":"test","usersurname":"test","cellnumber":"test","displayname":"test","profilepicture":"test","projects":[{"projectname":"test","dateadded":"test","notes":"test","image":"test"},{"task":[{"taskname":"test","taskdescription":"test","taskimage":"test"}]}]}]
//My for loop - All variables are declared prior
for(var i = 0; i < data.length; i++){
username = data[i].username;
console.log(username);
usersurname = data[i].usersurname;
cellnumber = data[i].cellnumber;
displayname = data[i].displayname;
profilepicture = data[i].profilepicture;
for(var j = 0; j < data[i].projects.length; j++){
dateadded = data[i].projects[j].dateadded;
console.log(dateadded);
notes = data[i].projects[j].notes;
image = data[i].projects[j].image;
for(var k = 0; k < data[i].projects[j].task.length; k++){
taskname = data[i].projects[j].task[k].taskname;
console.log(taskname);
taskdescription = data[i].projects[j].task[k].taskdescription;
taskimage = data[i].projects[j].task[k].taskimage;
}
}
}

Please check undefined end errors in your code. if something is undefined loop will break.
for (var i = 0; i < data.length; i++) {
username = data[i].username;
console.log(username);
usersurname = data[i].usersurname;
cellnumber = data[i].cellnumber;
displayname = data[i].displayname;
profilepicture = data[i].profilepicture;
if("undefined" != typeof (data[i].projects))
{
for (var j = 0; j < data[i].projects.length; j++) {
dateadded = data[i].projects[j].dateadded;
console.log(dateadded);
notes = data[i].projects[j].notes;
image = data[i].projects[j].image;
if ("undefined" != typeof (data[i].projects[j].task)) {
for (var k = 0; k < data[i].projects[j].task.length; k++) {
taskname = data[i].projects[j].task[k].taskname;
console.log(taskname);
taskdescription = data[i].projects[j].task[k].taskdescription;
taskimage = data[i].projects[j].task[k].taskimage;
}
}
}
}
}

Related

Data conditioning of google gmails/email addresses

I am trying to make filters for gmail and I need to get the sent TO emails.
The problem is that the emails in the To line of the email can have many different formats. I wanted to see if there was an easier way than what I was doing to unify the formats of the emails. I was just going to account for every case I could find and deal with like that.
function getTo(email) {
// Logs the To lines of up to the first 1-500 emails in your Inbox
var threads = GmailApp.getInboxThreads(0, 75);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var emailto = messages[j].getTo();
//runs the .to emails through the data conditioning function
//emailprocess(email,emailto)
}
Logger.log(emailto);
}
}
function main () {
var email = Session.getActiveUser().getEmail();
Logger.log(email);
getTo(email)
// createToFilte(toAddress, labelName)
}
function emailprocess(email,emailto){
var emailto = emailto.toLowerCase();
switch (emailto) {
case email:
label = 0;
break;
case "john doe <johndoe#gmail.com>":
label = 0;
break;
case "<johndoe#gmail.com>":
label = 0 ;
break;
default:
label = emailto.replace('johndoe+', '');
label = label.replace("#gmail.com","")
break;
}
}
The emails can be in many different formats here are some:
john doe < johndoe#gmail.com >
johndoe#gmail.com
< johndoe#gmail.com >
johndoe#gmail.com , janedoe#gmail.com
johndoe+65#gmail.com
and maybe only a little more.
Any help would be great. I am also not the best programmer so any way to make this more streamlined would be great.
Solution:
function getTo(email) {
var emailregex = /([a-zA-Z0-9_\.\+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-\.]+)/gm
var threads = GmailApp.getInboxThreads(0, 500); // Logs the To lines of up to the first 1-500 emails in your Inbox
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var emailto = messages[j].getTo()
var emailto = emailto.toLowerCase();
//Logger.log(emailto);
emailto = emailto.match(emailregex); //runs the .to emails through the data conditioning
Logger.log(emailto);
if(emailto != null){
for (var k = 0; k < emailto.length; k++) {
if (emailto[k].indexOf("+") > -1) {
var labelto = emailto[k].slice(emailto[k].indexOf("+") + 1, emailto[k].indexOf("#"));
createToFilter(emailto[k], labelto)
Logger.log(emailto[k]);
Logger.log(labelto);
}
}
}
}
}
}
You can try an email regex (there are many out there), here is one example:
function getTo(email) {
var emailregex = /([a-zA-Z0-9_\.\+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-\.]+)/gm
// Logs the To lines of up to the first 1-500 emails in your Inbox
var threads = GmailApp.getInboxThreads(0, 75);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var emailto = messages[j].getTo().match(emailregex);
//runs the .to emails through the data conditioning function
//emailprocess(email,emailto)
}
Logger.log(emailto);
}
}

replace string using array in javascript

abc1 abc2 abc3
abc4 abc5 abc6
abc7 abc8 abc9
using above csv file, load text by replacing the double quotes from the bellow sentence.
Sentence:
"" is going with "" to "" for something to know.
Expected out put is:
abc1 is going with abc2 to abc3 for something to know.
abc3 is going with abc5 to abc6 for something to know.
like this in javascript, php.
Code I have tried so far:
var s = 'Neque porro "" estqui "" dolorem';
var insert = [["a1", "b1"]["c1","d1"]];
console.log(insert);
var words = new Array();
words = s.split(" ");
console.log(words);
var count = 0;
for (i = 0; i < words.length; i++) {
for (j = 0; j < insert.length; j++) {
if(words[i] == '""')
s = s.replace(/""/, insert[j]);
}
}
console.log(s);
Hurray I got the answer:
reader.onload = function (e) {
var sent = ''; var sentt = ''; var senttt = '';
sent = $('#mixmsg').val();
var quoteLength = (sent.match(/""/g) || []).length;
var rowcells = [];
rows = e.target.result.split("\n"); alert(rows);
for (var i = 0; i < rows.length; i++) {
var cells = rows[i].split(",");
rowcells.push(cells);
}
var rowcellso = rowcells.slice(0, -1);
console.log(rowcellso);
for (var ro = 0; ro < rowcellso.length; ro++) {
for (var scol = 0; scol < quoteLength; scol++) {
sent = sent.replace(/""/,rowcellso[ro][scol]);
console.log(rowcellso[ro][scol]);
} sentt +=sent+'\n'; sent= $('#mixmsg').val();
}
$('#container').html(sentt);
}

finding and placing a word from the text in an array

I am trying to find a word in the text with my name. The code requires me to first find the first character of the word and then subsequently push the remaining letters in the hits[] array. I am trying but got stuck.
var text = "This is just Rohit.";
var myName = "Rohit";
var hits = [];
for (var i = 0; i < text.length; i++)
{
if(text[i] === myName[0] )
{
for(j = 0; j < myName.length; j++)
{
hits.push(text[i]);
};
};
};
hits;
var text = "This is just Rohit.";
var myName = "Rohit";
var hits = [];
for (var i = 0; i < text.length; i++) {
if(text[i] === myName[0] ) {
for(var j = i, l = 0; l < myName.length; j++, l++) {
hits.push(text[j]);
}
}
}
console.log(hits.join(''));
Just ignore the searchtext and go with the searchterm.
var hits = [];
var i=0;
while (i<"Rohit".length) arr.push("Rohit"[i++]);
console.log(hits);
// ["R", "o", "h", "i", "t"]
Something like this should help.Let me know if a change is needed.
var text = "This is just Rohit.";
var myName = "Rohit.";
var hits = [];
var array1=text.split(" ");
for (var i = 0; i < array1.length; i++)
{
if(array1[i]==myName)
{
hits.push(array1[i].split(''));
}
}
THIS PART IS THE METHOD WHICH YOU WERE USING::
var text = "This is just Rohit.";
var myName = "Rohit";
var hits = [];
var x='';
for (var i = 0; i < text.length; i++)
{
if(text[i] === myName.charAt(0) && text[i-1]==" " )
{
for(j = i; j < (i+myName.length); j++)
{
console.log(text[j]);
x=x+text[j];
}
}
}
hits[0]=x;
alert(hits);
After looking at your comments for clarification, it looks like you just want your name as the only element in a new array.
Use this:
var text = 'Your name is Rohit.';
var name = 'Rohit';
var hits = [text.substring(text.indexOf(name), text.indexOf(name) + name.length)];
console.log(hits);
// ["Rohit"]
Can't imagine how this is helpful, but the code above will do what you want.
I solved it.
var text = "This is just Rohit.";
var myName = "Rohit";
var hits = [];
for (var i = 0; i < text.length; i++)
{
if(text[i] === myName[0] )
{
for(var j = i; j < (myName.length+i); j++)
{
hits.push(text[j]);
};
};
};
hits;

How do i display the longest array in JS?

I want to create a Javascript array of words, then use Javascript to find the longest word and print it to the screen. Here is my code:
var StrValues = []
StrValues[0] = ["cricket"]
StrValues[1] = ["basketball"]
StrValues[2] = ["hockey"]
StrValues[3] = ["swimming"]
StrValues[4] = ["soccer"]
StrValues[5] = ["tennis"]
document.writeln(StrValues);
You can use length to find the longest string in a array. Here is a fiddle http://jsfiddle.net/2sebnb33/1/
for(var i=0;i<StrValues .length;i++){
if(StrValues [i].length>len){
len=StrValues [i].length;index=i;}
}
var strValues = ["cricket", "basketball", "hockey"];
var max = '';
for(var i = 0; i< strValues.length; i++) {
max = strValues[i].length > max.length ? strValues[i] : max;
}
alert(max);
Firstly, you need to correct the way you are creating array.
For instance, it should be like this
var StrValues = [];
StrValues[0] = ["cricket"];
The logic
var longestWord = "";
for (var i = 0 ; i < StrValues.length; i++) {
if(StrValues[i].length > longestWord.length) {
longestWord = StrValues[i];
}
}
See the code below:
var array = [];
array.push("cat");
array.push("children");
array.push("house");
array.push("table");
array.push("amazing");
var maxSize = 0;
var maxSizeWord = "";
for(var i = 0; i < array.length; i++) {
if (maxSize < array[i].length) {
maxSize = array[i].length;
maxSizeWord = array[i];
}
}
alert("The biggest word is '" + maxSizeWord + "' with length '" + maxSize + "'!");

What is wrong with this javascript codes

see the code.
Thanks for the help everyone. Much appreciated for the valuable feedback. But it haven't helped. I really thank you.
$.get("http://nominatim.openstreetmap.org/search?q=pekin,+china&format=json&polygon=1&addressdetails=1").done(function(data)
{
var aJsonData = new Array();
var iBiggest = 0;
aJsonData = JSON.parse(data);
aData = aJsonData;
for(var i=0; i < aData.length; i++)
{
if(i != 0)
{
if((aData[i].polygonpoints.length) > (aData[iBiggest].polygonpoints.length))
{
iBiggest = i;
}
}
}
alert(iBiggest);
for(var j=0; j < aData[iBiggest].polygonpoints.length; j++)
{
//alert(aData[iBiggest].polygonpoints[j]);
}
});
Your for loop is wrong, the array index will start from 0 to length - 1 so i <= aData.length is wrong.
So the loop should be
$
.get("http://nominatim.openstreetmap.org/search?q=london,+england&format=json&polygon=1&addressdetails=1")
.done(function(data) {
var iBiggest = 0;
for (var i = 1; i < data.length; i++) {
if ((data[i].polygonpoints.length) > (data[iBiggest].polygonpoints.length)) {
iBiggest = i;
}
}
// this is not working
alert(iBiggest);
for (var j = 0; j < data[iBiggest].polygonpoints.length; j++) {
// alert(aData[iBiggest].polygonpoints[j]);
}
}, 'json');
Demo: Fiddle
I solved it.
$.getJSON("http://nominatim.openstreetmap.org/search?q=pekin,+china&format=json&polygon=1&addressdetails=1", function(data)
{
var iBiggest = 0;
for(var i = 1; i < data.length; i++)
{
if(data[i].polygonpoints != 'undefined' && data[i].polygonpoints)
{
if((data[i].polygonpoints.length) > (data[iBiggest].polygonpoints.length))
{
iBiggest = i;
}
}
}
alert(iBiggest);
for(var j = 0; j < data[iBiggest].polygonpoints.length; j++)
{
alert(data[iBiggest].polygonpoints[j]);
}
});

Categories