SQL + Javascript - Multiple fields into something I can loop through? - javascript

I have two fields I need to pull data from in SQL and put that into an array or list that I can loop through. Then for each loop, I do something based on both the fields for each index. What is the best method for this? I thought maybe a dictionary or possibly creating an object?
Right now I pull the fields into two seperate arrays, and I loop through both at the same time, but I am finding that sometimes one array has a blank value, and then they get out of sync and I have issues. This seems like a terrible implementation anyway.
How can I put these into a key value pair and then act on the data?
Edit: I should note that my SQL code just returns a bunch of comma seperated values. So it was easy to create an array out of those, but its proving more difficult to create anything else such as an object because I get all the values at one time.. :(
var equipIDArray = //SQL Gathering code here
var equipTypeArray = //SQL gathering code here
for(var cnt = 0; cnt < equipIDArray.length; cnt++){
alert(cnt);
if(isNaN(equipIDArray[cnt]) === true){
equipIDArray[cnt] = '';
}
switch(equipTypeArray[cnt]){
case 'Blower' :
alert('test1');
break;
case 'Dehumidifier' :
alert('test2');
break;
default :
alert('default');
}
}

It' easy to translate your arrays into an object if they just represent key/value pairs. Then you have an object you can use like a dictionary:
var equipIDArray = ["Blower","Humidifier","Lawn Mower"];
var equipTypeArray = ["Leaf blower","Whole House Humidifier","Honda Brand"];
var equipment = {};
for(var i = 0; i < equipIDArray.length; i++) {
equipment[equipIDArray[i]] = equipTypeArray[i];
}
for(property in equipment) {
console.log(property + " : " + equipment[property]);
alert(property + " : " + equipment[property]);
}

Related

Merging Multiple Arrays Evenly/Alternating with Javascript and Google AppScript

I'm trying to merge multiple arrays evenly/alternating in javascript/Google appScript. There are several arrays (5 or 6). I've tried 2 different methods, but neither worked. I don't work a lot with javascript honestly and I've managed to get the code to this point, but I can't get it merge properly; and most of them said merging two arrays to one (might be my problem).
I've seen plenty on php examples that were on how to do this and they are pretty straight forward in logic reading and I understand them better, but all javascript methods I've looked at and tried so far have failed to produce the results I want. I'm not sure if it's the way AppScript is formatting the arrays or they're just no made to handle more that 2.
My data looks similar to this at the moment:
var title = ["sometitle1","sometitle2","sometitle3"];
var link = ["somelink1","somelink2","somelink3"];
var date = ["somedate1","somedate2","somedate3"];
var data = ["somedata1","somedata2","somedata3"];
var all = [title,link,date,data];
var mix = [];
Note: all the variable data will/should be the same length since the data is being pulled from a spreadsheet.
My desired output is:
mix = ["sometitle1","somelink1","somedate1","somedata1","sometitle2","somelink2","somedate2","somedata2","sometitle3","somelink3","somedate3","somedata3"];
I tried using appscript to merge them with this: return ContentService.createTextOutput(title + link + data + date), but it didn't work out properly, it printed them in that order instead of merging the way I'd like them too.
Then I tried using a loop merge that I found here on sstackoverflow:
for (var i = 0; all.length !== 0; i++) {
var j = 0;
while (j < all.length) {
if (i >= all[j].length) {
all.splice(j, 1);
} else {
mix.push(all[j][i]);
j += 1;
}
}
}
But it splice merges every letter with a comma
mix = [s,o,m,e,t,i,t,l,e,1,s,o,m,e,t,i,t,l,e,2,s,o,m,e,t,i,t,l,e,3,s,o,m,e,l,i,n,k,1,...]
and doesn't alternate data either.
The code (2 version) I'm working on is: here with Output
&
Here with Output
(Also, dumb question, but do I use title[i] + \n OR title[i] + "\n" for adding new lines?)
Use a for loop and the push() method like this :
function test(){
var title = ["sometitle1","sometitle2","sometitle3"];
var link = ["somelink1","somelink2","somelink3"];
var date = ["somedate1","somedate2","somedate3"];
var data = ["somedata1","somedata2","somedata3"];
//var all = [title,link,date,data];
var mix = [];
for(var n=0;n<title.length;n++){
mix.push(title[n],link[n],date[n],data[n]);
}
Logger.log(JSON.stringify(mix));
}
And also : title[i] + "\n" for adding new lines
Edit following comments :
Your code should end like this :
...
for(var n=0;n<titles.length;n++){
mix.push(titles[n],links[n],descriptions[n],pubdates[n],authors[n]);
}
var mixString = mix.join('');// convert the array to a string without separator or choose the separator you want by changing the argument.
//Print data and set mimetype
return ContentService.createTextOutput(mixString)
.setMimeType(ContentService.MimeType.RSS);
}

Pushing object to array results in same value

I have the following javascript code that does not work as I would expect it to. I have a list of checkboxes of which two of the items are "TestDuration" and "AssessmentScores". I'm trying to iterate through the list (which works fine) and have it add the values that are checked to the array.
var SAIndex = 0;
var SSIndex = 0;
var ScoresIndex = 0;
var SubAssessments = [];
var SubAssessmentScores = [];
//Get to the container element
var SSList = document.getElementById("islSubAssessmentScore_container");
//turn it into an array of the checkbox inputs
SSList = SSList.getElementsByTagName("input");
//create a temporary object to store my values
var tempPair = new Object();
//iterate through the checkbox lists
for(var i = 1; i < SSList.length;i++)
{
//if the value is checked add it to the array
if (SSList[i].checked)
{
var P = SubAssessments[SAIndex];
var V = SSList[i].value;
//tempPair.Parent = SubAssessments[SAIndex];
tempPair.Parent = P;
//tempPair.Value = SSList[i].value;
tempPair.Value = V;
//show me the values as they exist on the page
alert(tempPair.Parent + "|" + tempPair.Value);
SubAssessmentScores.push(tempPair);
//show me the values I just added to the array
alert(SubAssessmentScores.length-1 + "|" + SubAssessmentScores[SubAssessmentScores.length-1].Parent + "|" + SubAssessmentScores[SubAssessmentScores.length-1].Value);
//uncheck the values so when I refresh that section of the page the list is empty
SSList[i].checked = false;
}
}
//output the list of objects I just created
for (i = 0;i < SubAssessmentScores.length;i++)
alert(i + "|" + SubAssessmentScores[i].Parent + "|" + SubAssessmentScores[i].Value)
Now what happens is that when I iterate through the list I get the following alerts:
-first pass-
StudentID|TestDuration
0|StudentID|TestDuration
-second pass-
StudentID|AssessmentScores
1|StudentID|AssessmentScores
This is what I expect to output... However at the end of the code snippet when it runs the for loops to spit out all the values I get the following alerts...
0|StudentID|AssessmentScores
1|StudentID|AssessmentScores
I can't for the life of me figure out why it's replacing the first value with the second value. I thought it might be using a reference variable which is why I added in the P and V variables to try to get around that if that was the case, but the results are the same.
This is because you are adding the same variable every iteration of the loop.
Try changing your push like this:
SubAssessmentScores.push({
Parent: P,
Value: V
});
That said, I recommend you study a little more javascript and conventions in the language, for example your variable naming is frowned upon because you should only use capital letters on the beginning of a name for constructor functions.
A good book is Javascript the good parts by Douglas Crockford.

problems when receiving form array with only one element in javascript

I am receiving a html form. This works fine when 2 or more elements in array, but when only one element is received I get error users[t] is null in fireBug?
var users = form.elements["uname[]"];
for(t in users) {
dataString += "User: "+users[t].value+"\n"
}
this solved it:
if( typeof users.value === 'string' ) {
users = [ users ];
}
I know this is an old question but I stumbed across it while searching for something else. Anyway, I thought I'd provide another answer for anyone else who stumbled across this.
Rather than checking the type to see if it is an array or not and then optionally encasing the value in a new array, you can use Array.prototype.concat().
Its syntax is
var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
where any of those values can be either an array or a single value.
In your specific case, you can start with an empty array and concatenate your form input, which will work whether you get a single value or an array:
var users = [].concat(form.elements["uname[]"]);
or
users = [].concat(users);
You could check if the variable is a string and convert it to an array:
if( typeof users === 'string' ) {
users = [ users ];
}
For iterating arrays for-in should be avoided, that statement is meant to enumerate object properties. You could try using a better loop, something like:
var userCount = users.length;
for (var i = 0; i < userCount; i++) {
dataString += "User: "+users[i].value+"\n"
}
You could also base a test on the length. If the object is single it will return undefined for length.
var userCount = users.length; //Get user count
if ( userCount == undefined ) { //Returned undefined if not an array.
users = [ users ]; //Convert to array
}

Storing and retrieving objects in javascript array();

Hi I've searched for the answer but since the tutorials online are all friends = ("bob","fred","joe"); I dont get anywhere. I would like to be able to store several objects with 1-3 values in each index of the array like:
map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}]
The object I have right now looks like:
node = {};
node = {ground:0, object:1};
But when I try the array way I can't access it, all I get "object Object". What would be the correct way to get the values from the map array one by one?
Do you mean:
var map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}];
for(var i = 0; i < map.length; i++) {
console.log(map[i].ground + " item " + map[i].item);
}
Not sure what you want, or what you mean by "the array way", but if you want to get all the values for say ground, then:
var map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}]
for (var i=0, iLen=map.length; i<iLen; i++) {
alert(map[i].ground);
}
Edit
...
alert('item ' + i + ' : ' + map[i].ground); // item 0 : 0
...

fastest way to loop through an array

I want to return an array when one of the elements matches an item within an array.
Is the below code the fastest way to loop through an array when a value matches in a javascript array of arrays?
Note : Welcome any suggestions to modify the variable relatedVideosArray to make it a different data structure for better performance.
var relatedVideosArray = [
["1047694110001"],
["1047694111001", "1019385098001","1020367665001","1020367662001", "1019385097001", "1020367667001"],
["1040885813001"],
["1019385094001", "1019385096001"],
["952541791001", "952544511001", "952544512001", "952544508001", "952541790001","952580933001", "952580934001", "1051906367001"]
]
function getRelatedVideos(videoClicked){
var tempStoreArray = [];
var getCurrentId = videoClicked;
var relVideoslen = relatedVideosArray.length;
for(var i in relatedVideosArray) {
tempStoreArray = relatedVideosArray[i];
for(var j in tempStoreArray){
if(tempStoreArray[j] == getCurrentId){
return relatedVideosArray[i];
}
}
}
}
Update: I initially thought of making a key of video ids and values as all the related ids, but I want to display the key as well as all the related ids if any of the ids within the value array are clicked. Hope this helps to explain the constraint I have.
Modern day browsers support Array indexOf.
For the people saying the array indexOf is slower, basic tests on speed.
var values = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
console.time("for");
for(var i=0;i<1000;i++){
for(var j=0;j<=values.length;j++){
if(values[j]===20) break;
}
}
console.timeEnd("for");
console.time("reverse for");
for(i=0;i<1000;i++){
for(var j=values.length-1;j>=0;j--){
if(values[j]===1) break;
}
}
console.timeEnd("reverse for");
console.time("while");
for(i=0;i<1000;i++){
var j=0;
while (j<values.length){
if(values[j]===20) break;
j++;
}
}
console.timeEnd("while");
console.time("reverse while");
for(i=0;i<1000;i++){
var j=values.length-1;
while (j>=0){
if(values[j]===1) break;
j--;
}
}
console.timeEnd("reverse while");
console.time("indexOf");
for(var i=0;i<1000;i++){
var x = values.indexOf(20);
}
console.timeEnd("indexOf");
console.time("toString reg exp");
for(var i=0;i<1000;i++){
var x = (/(,|^)20(,|$)/).test(values.toString);
}
console.timeEnd("toString reg exp");
Two possible solutions:
var relatedVideosArray = [
["1047694110001"],
["1047694111001", "1019385098001","1020367665001","1020367662001", "1019385097001", "1020367667001"],
["1040885813001"],
["1019385094001", "1019385096001"],
["952541791001", "952544511001", "952544512001", "952544508001", "952541790001","952580933001", "952580934001", "1051906367001"]
]
//var getCurrentId = "1019385098001";
var getCurrentId = "1040885813001";
console.time("indexOf");
var tempStoreArray = [];
for(var i = relatedVideosArray.length-1; i>=0; i--){
var subArr = relatedVideosArray[i];
if(subArr.indexOf(getCurrentId)!==-1){
tempStoreArray.push(subArr);
}
}
console.timeEnd("indexOf");
console.log(tempStoreArray);
console.time("toString reg exp");
var tempStoreArray = [];
var re = new RegExp("(,|^)" + getCurrentId + "(,|$)");
for(var i = relatedVideosArray.length-1; i>=0; i--){
var subArr = relatedVideosArray[i];
if(re.test(subArr.toString())){
tempStoreArray.push(subArr);
}
}
console.timeEnd("toString reg exp");
console.log(tempStoreArray);
I believe so if you keep your current structure. Unless you have a way of 'flattening' the array first, so that rather than being nested, there is simply one array with all the values. If this is out of your control or impractical, then you have no other choice than to iterate over every element and its elements.
Otherwise, would you be able to add the values to a map? The current video id would be the key, and the value would be the list of related videos.
If you have control over the data structure then I highly recommend changing it to something more amenable to the type of searches you are performing. First thing that comes to mind is an array of associative arrays. Each of your video arrays would be keyed with the video id ( set the value to anything you want ). That would make your search O(n), where n = the total number of video lists you have.
I'll post some code for this when I get in front of the computer.

Categories