Push to array with index method (JavaScript) - javascript

I am having difficulty pushing objects to an array of arrays via indices. Find below my current (awfully duplicative code) which reads through a CSV file's lines (Format: Date, reasonCode), and then creates FROM and TO (date) pairs depending on the reasonCode. This array is then used for Highcharts (Gantt chart). Please note the fromto1 and fromto2 arrays.
csv = csv.split(/\n/g);
var fromto1 = []; //array of FROM and TO pairs of code 1
fromto2 = []; //array of FROM and TO pairs of code 2
count = [];
lastFrom = [];
for (var i=1;i<3;i++) { //set all count and lastFrom variables to 0 //bs
count[i] = 0;
lastFrom[i] = 0;
}
jQuery.each(csv, function(i, line) {
line = line.split(','); //splits line, returns array of splitted values
date = parseInt(line[0], 10)*1000; //read date from line into string
reasonC = parseInt(line[2], 10); //read reasonC from line into string
if (reasonC == "1") {
count[1]++;
if (count[1] % 2 !=0){ //if it is an uneven value (FROM values)
lastFrom[1] = date; //temporary save the date in lastFrom[]
}
else { //if it is an even value (TO value), push the pair
fromto2.push({
from: lastFrom[1],
to: date
});
}
}
if (reasonC == "2") {
count[2]++;
if (count[2] % 2 !=0){
lastFrom[2] = date;
}
else {
fromto3.push({
from: lastFrom[2],
to: date
});
}
}
Why can't I replace the above code with this (Please note the fromto array of arrays):
csv = csv.split(/\n/g);
var fromto = [];
count = [];
lastFrom = [];
for (var i=1;i<3;i++) { //set all count and lastFrom variables to 0
count[i] = 0;
lastFrom[i] = 0;
fromto.push(new Array());
console.log(i+': New Array Pushed');
}
jQuery.each(csv, function(i, line) {
line = line.split(','); //splits line, returns array of splitted values
date = parseInt(line[0], 10)*1000; //read date from line into string
reasonC = parseInt(line[2], 10); //read reasonC from line into string
for (var c=1;c<3;c++) {
if (reasonC == c.toString()) {
count[c]++;
if (count[c] % 2 !=0){ //if it is an uneven value (FROM values)
lastFrom[c] = date; //temporary save the date in lastFrom[]
}
else { //if it is an even value (TO value), push the pair
fromto[c].push({
from: lastFrom[c],
to: date
});
}
}
}
}
I believe the problem is with fromto[c].push({ as it stays blank arrays.
I'm still a Jsnoob and couldn't find any answers on other threads, your help would be highly appreciated

There's quite a few things in your JavaScript that can do with some tips on how to do what you want to do using best practices, so an answer + advice.
1) multiple variables in a single declaration are separated by commas, not semi-colos:
var csv = csv.split(/\n/g),
fromto = [],
count = [],
lastFrom = [];
2) Don't use the Array object for making arrays.
fromto.push([]);
3) JS has function scoping only if you use var. Without var, variables are global.
jQuery.each(csv, function(i, line) {
line = line.split(',');
var date = parseInt(line[0], 10)*1000,
reasonC = parseInt(line[2], 10);
4) == is a coercing equality, and will see if there is any way two values can be considered the same. 4 == "4" is true, 4 === "4" is not.
if (reasonC == c) { ...
or
if (reasonC === c.toString()) { ...
5) JavaScript has forEach baked in, why would you use jQuery for something that's part of JavaScript already?
csv.forEach(function(line) {
...
});
And then the answer to your question, of course. It looks like you're trying to turn this data:
123,somevalue,1
456,somevalue,2
...
into this structure:
[
{ from: 123, to: 456 },
{ from: ..., to: ...},
...
]
You're relying on the line order to tell you which date is a from and which is a to; that's bound to go wrong, but you know your data best. (If I were writing this, I would operate on the assumption that line ordering is unknown)
var cvs = data.split(",");
parity = 0,
fields,
odd = [],
even = [],
fromTo = [];
cvs.forEach(function(line) {
parity = (parity + 1) % 2;
fields = line.split(",");
bin = parseInt(fields[2],10);
if(parity===1) {
odd[bin] = fields;
} else {
even[bin] = fields;
fromTo[bin].push({
from: odd[bin][0],
to: even[bin][0]
});
}
});
Now, this should work but this code is also really scary, because it still relies on line ordering in the CVS file, and without a hard guarantee that this is the case (like preprocessing validation), this (like your code) will do horrendously wrong things the moment two lines are accidentally in the wrong order.

Related

ReferenceError on Array item

This should be a really simple script that changes the title of a column between 3 columns. I got it to work once, but now it's coming up with an error I don't understand:
ReferenceError: "Today" is not defined. (line 10, file "Code")
Code is as follows:
function Progressions() {
var workoutSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Workouts");
var Increment = workoutSheet.getRange(2, 1, 1, 3).getValues();
var newRoutine =[[]]
if (Increment == [[Today,,]]){
var newRoutine = [[ ,Today, ]]
Increment.setValues(newRoutine);
} else {
if (Increment == [[,Today,]]){
var newToday = [[,,Today]]
Increment.setValues(newRoutine);
} else {
if (Increment == [[,,Today]]){
var newToday = [[Today,,]]
Increment.setValues(newRoutine);
}
}
}
Obviously Today is not defined as that's just the content of the array.
I think this script should just change the content of the newToday array and then enter it into the todayIncrement range.
Any ideas how I can remove this error and achieve my goal?
There are several reasons why your code isn't working such as "Today" but also in your arrays with you call .getValues(); the returned array will be something like [["","Today",""]]
You can't use Increment.setValues(------); as increment is an array an not a range object.
The if statement should be constructed
if(-----){
} else if (-----) {
} else {
}
This code does as you require:
function Progressions() {
var workoutSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Workouts");
var range = workoutSheet.getRange(2, 1, 1, 3);
var increment = range.getValues();
var newRoutine;
var testValue = "Today";
if (increment[0][0] == testValue) {
newRoutine = [["", "Today", ""]];
} else if (increment[0][1] == testValue) {
newRoutine = [["", "", "Today"]];
} else if (increment[0][2] == testValue) {
newRoutine = [["Today", "", ""]];
}
range.setValues(newRoutine);
}
An alternate implementation of the if-else chain that is easier to extend (e.g. if you had 365 different workouts as columns, the above method needs 365 if-else checks), at the cost of needing more JavaScript knowledge to understand how it works:
function Progressions() {
const workoutSheet = SpreadsheetApp.getActive().getSheetByName("Workouts"),
// 1 column per workout (here we have 3).
headerRange = workoutSheet.getRange(2, 1, 1, 3),
// Assume headers are in the range's first row.
headers = headerRange.getValues()[0],
newRoutine = [];
// Use Array#indexOf to do all the nasty "if-else if" checking.
const searchValue = "Today";
const columnIndex = headers.indexOf(searchValue);
if (columnIndex === -1)
throw new Error("'" + searchValue + "' not found in headers ('" + headerRange.getA1Notation() + "').");
// Set default header values (no Array#fill in Apps Script yet).
headers.forEach(function (s) { newRoutine.push(""); });
// Use addition and the modulus operator to increment and wrap.
const newIndex = (columnIndex + 1) % newRoutine.length;
newRoutine[newIndex] = searchValue;
// Write the new header values.
headerRange.setValues( [newRoutine] );
}

Getting Incorrect range height for seemingly no reason?

I am writing a script to copy and paste a range from one sheet to another. The pasted range size should be reduced by using two functions : one to delete rows with specific values and the other is an aggregate function.
I started getting this error after I introduced the aggregate function The function is basically reducing the array size using the reduce JS function.
I have replicated my problem here and the code is accessible in the script editor.
When I run the script I am getting the following error :
Incorrect range height was 28 but should be 7 (line 36, file "test")
I have no idea why am I getting this error. My aggregate function returns a properly formatted array with the right length.
function append_range(){
var origin_sheet = SpreadsheetApp.openById('1-2ZheMz1p01qwtwY3ghbNjJedYfGXeylnLEjDMCLpMw');//open the file
origin_sheet = origin_sheet.getSheetByName('test');
var rangeStart = 2;
var range = origin_sheet.getRange('A'+ (rangeStart.toString())+':T'+ (origin_sheet.getLastRow()).toString());
var dataFromRange = range.getValues();
var dataFromRangeLength = dataFromRange.length;
var destination_sheet = SpreadsheetApp.openById('1-2ZheMz1p01qwtwY3ghbNjJedYfGXeylnLEjDMCLpMw');
destination_sheet = destination_sheet.getSheetByName('append');
var rowLast = destination_sheet.getLastRow()+1;
Logger.log("row last" + rowLast);
var formattedRange = deleteRows(dataFromRange);
var groups = aggregate(formattedRange);
var aggregates = [];
for(var group in groups)
{
aggregates.push(groups[group]);
}
Logger.log(aggregates);
var formattedRangeLength = aggregates.length;
Logger.log("formattedRangeLength" + formattedRangeLength);
destination_sheet.getRange(rowLast,1,formattedRangeLength, 20).setValues(deleteRows(dataFromRange));
function isDate(sDate) {
if (isValidDate(sDate)) {
sDate = Utilities.formatDate(new Date(sDate), "PST", "yyyy-MM-dd");
}
return sDate;
}
function isValidDate(d) {
if ( Object.prototype.toString.call(d) !== "[object Date]" )
return false;
return !isNaN(d.getTime());
}
//
function deleteRows(dataRange){//just pass the range in an array and this method will return another array with filtered range
var formatted = dataRange.filter(function(e) {
return e[8]||e[9]||e[10]||e[11]||e[12]||e[13]||e[14]||e[15]||e[16]||e[17]||e[18]||e[19];
});
return formatted;
}
function aggregate(data)
{
var groups = data.reduce(
function(accumulator, previous){
{
var key = previous[1] + previous[3] + previous[5] + previous[6];
var group = accumulator[key];
if(group == null || typeof group == 'undefined')
{
accumulator[key] = previous;
}
else {
var startIndex = 8;
for(var i = startIndex; i < previous.length;i++)
{
group[i] += previous[i];
}
}
return accumulator;
}},
{});
return groups;
}
}
The .setValues() is not setting your aggregates array it is trying to set deleteRows(dataFromRange)
// Change the setValues() to your reduced array
destination_sheet.getRange(rowLast,1,formattedRangeLength, 20).setValues(aggregates);
I think this might work:
var output=deleteRows(dataFromRange));
destination_sheet.getRange(rowLast,1,output.length, output[0].length).setValues(deleteRows(output));
This assumes a non jagged array.

JavaScript Dynamically created object undefined

I am doing the freecodecamp algorithmic challenge "Caesars Cipher". I have a problem with my code. I try to generate a lookup table as a dynamic object and for some reason it doesn't register. When doing console.log it is says "lookup table is undefined". It is the same with the Acode variable. If I comment out the console.logs then it will work but it will not encrypt anything because of the below part which checks if the char from strArr exists in the lookupTable, if not, it should assign the same value to the encryptedArr (this was done to not encrypt commas, spaces etc):
strArr.forEach(function(thisArg) {
var newValue;
if(lookupTable[thisArg] !== undefined ) {
newValue = lookupTable[thisArg];
} else {
newValue = thisArg;
}
encryptedArr.push(newValue);
});
Ofcourse lookupTable[thisArg] is always undefined.
Here is the whole function with the above part as well:
function rot13(str) { // LBH QVQ VG!
var strArr;
var encryptedArr = [];
var Acode;
var lookupTable = {}; //this object will contain the mapping of letters
var encryptedString;
//check the code of A , this will be a reference for the first letter as the algorith will use Modular Arithmetic
Acode = 'A'.charCodeAt(0);
console.log(Acode);
//generate an object containing mappings (I din't want to do it initially but theoreticaly just making lookups in a table would be more efficiant for huge workloads than calculating it every time)
//this algorithm is a little bit complecated but i don't know how to do modular arithmetic in code properly so I use workarrounds. If a = 101 then I do 101 + the remainder from current letter((Acode + 1) - 13) divided by 26 which works
for (i = 0; i < 26; i++) {
lookupTable[String.fromCharCode(Acode + i)] = String.fromCharCode(Acode + ((Acode + i) - 13) % 26);
console.log(lookupTable[String.fromCharCode(Acode + i)]);
}
//save the string into the array
strArr = str.split("");
//change letters into numbers and save into the code array
strArr.forEach(function(thisArg) {
var newValue;
if (lookupTable[thisArg] !== undefined) {
newValue = lookupTable[thisArg];
} else {
newValue = thisArg;
}
encryptedArr.push(newValue);
});
encryptedString = encryptedArr.join("");
return encryptedString;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
console.log(Acode);
What am I doing wrong with the lookupTable object creation AND with the below?
Acode = 'A'.charCodeAt(0);
There's no undefined variable. The problem with your code is in how you calculate the lookup table entries. Your code is mapping every character to itself, not shifting by 13. The correct formula is
Acode + ((i + 13) % 26)
Acode is the ASCII code for the letter, and you shouldn't be including that when performing the modular shift. You just want to apply the modulus to the offset from the beginning of the alphabet after shifting it by 13.
function rot13(str) { // LBH QVQ VG!
var strArr;
var encryptedArr = [];
var Acode;
var lookupTable = {}; //this object will contain the mapping of letters
var encryptedString;
//check the code of A , this will be a reference for the first letter as the algorith will use Modular Arithmetic
Acode = 'A'.charCodeAt(0);
// console.log(Acode);
//generate an object containing mappings (I din't want to do it initially but theoreticaly just making lookups in a table would be more efficiant for huge workloads than calculating it every time)
//this algorithm is a little bit complecated but i don't know how to do modular arithmetic in code properly so I use workarrounds. If a = 101 then I do 101 + the remainder from current letter((Acode + 1) - 13) divided by 26 which works
for (i = 0; i < 26; i++) {
lookupTable[String.fromCharCode(Acode + i)] = String.fromCharCode(Acode + ((i + 13) % 26));
// console.log(lookupTable[String.fromCharCode(Acode + i)]);
}
//save the string into the array
strArr = str.split("");
//change letters into numbers and save into the code array
strArr.forEach(function(thisArg) {
var newValue;
if (lookupTable[thisArg] !== undefined) {
newValue = lookupTable[thisArg];
} else {
newValue = thisArg;
}
encryptedArr.push(newValue);
});
encryptedString = encryptedArr.join("");
return encryptedString;
}
// Change the inputs below to test
var result = rot13("SERR PBQR PNZC");
console.log(result);

Send emails from two distinct columns using data in google spreadsheets

Good morning.
Very new coder with little background. I need to merge data from a google spreadsheet into an email, without using an add-on. I borrowed this code from a site and I'm able to produce an email but it will only pull from the first email address column. I need to send an email to both the manager and director. Their email address will be stored in two separate columns with unique labels. I can't change the spreadsheet data as the spreadsheet is storing responses pulled from a survey form that is already in progress (example column layout below):
Name / Email Address / Director Name / Director Email Address / Response 1 / Response 2 / etc...
Everything I've researched will send an email from one column, but not two, or a "cc".
Below is the borrowed code. Would very much appreciate any help on how to modify the code to send the "response" data to both the Manager and Director in one email.
kind regards,
KA
function sendEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dataSheet = ss.getSheets()[0];
var dataRange = dataSheet.getRange(2, 1, dataSheet.getMaxRows() - 1, 15);
var templateSheet = ss.getSheets()[1];
var emailTemplate = templateSheet.getRange("A1").getValue();
// Create one JavaScript object per row of data.
var objects = getRowsData(dataSheet, dataRange);
// For every row object, create a personalized email from a template and send
// it to the appropriate person.
for (var i = 0; i < objects.length; ++i) {
// Get a row object
var rowData = objects[i];
// Generate a personalized email.
// Given a template string, replace markers (for instance ${"First Name"}) with
// the corresponding value in a row object (for instance rowData.firstName).
var emailText = fillInTemplateFromObject(emailTemplate, rowData);
var emailSubject = "Data Survey";
MailApp.sendEmail(rowData.emailAddress, emailSubject, emailText);
}
}
// Replaces markers in a template string with values define in a JavaScript data object.
// Arguments:
// - template: string containing markers, for instance ${"Column name"}
// - data: JavaScript object with values to that will replace markers. For instance
// data.columnName will replace marker ${"Column name"}
// Returns a string without markers. If no data is found to replace a marker, it is
// simply removed.
function fillInTemplateFromObject(template, data) {
var email = template;
// Search for all the variables to be replaced, for instance ${"Column name"}
var templateVars = template.match(/\$\{\"[^\"]+\"\}/g);
// Replace variables from the template with the actual values from the data object.
// If no value is available, replace with the empty string.
for (var i = 0; i < templateVars.length; ++i) {
// normalizeHeader ignores ${"} so we can call it directly here.
var variableData = data[normalizeHeader(templateVars[i])];
email = email.replace(templateVars[i], variableData || "");
}
return email;
}
//////////////////////////////////////////////////////////////////////////////////////////
//
// The code below is reused from the 'Reading Spreadsheet data using JavaScript Objects'
// tutorial.
//
//////////////////////////////////////////////////////////////////////////////////////////
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
var numColumns = range.getEndColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(range.getValues(), normalizeHeaders(headers));
}
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Returns an Array of normalized Strings.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum(letter)) {
continue;
}
if (key.length == 0 && isDigit(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
return char >= '0' && char <= '9';
}
According to the documentation : Mail App, the recipent represents the addresses of the recipients, separated by commas
So in order to send to several recipents, just make a string separated by comma:mike#example.com, mike2#example.com
You could pick the rows you want and do something like this:
MailApp.sendEmail(rowData[0].emailAddress + ',' + rowData[1].emailAdress, emailSubject, emailText);

Javascript Split Array and assign values to variables from NZBMatrix API

Not sure if any of you guys/girls out there that uses the NZBMatrix website API..
In short what I'm trying to do is build an Adobe Air Application,
using JavaScript, AJAX to connect to the API with a search query, this is all good.
When i receive the "request.responseText" back from the API with the 5 results
(can only be 5) I'm having trouble with the JavaScript split function trying to split them all out...
the return string is returned as follows:
NZBID:444027;
NZBNAME:test result 1;
LINK:nzbmatrix.com/nzb-details.php?id=444027&hit=1;
SIZE:1469988208.64;
INDEX_DATE:2009-02-14 09:08:55;
USENET_DATE:2009-02-12 2:48:47;
CATEGORY:TV > Divx/Xvid;
GROUP:alt.binaries.test;
COMMENTS:0;
HITS:174;
NFO:yes;
REGION:0;
|
NZBID:444028;
NZBNAME:another test;
LINK:nzbmatrix.com/nzb-details.php?id=444028&hit=1;
SIZE:1469988208.64; = Size in bytes
etc..etc..
the first Array should split each set of results using |
assign those 5 results to a new array.
the 2nd Array should split each value using :
assign those 12 results to new variables
ie: var nzbidtxt = array1[0]; which would echo like:
document.write(nzbidtxt); // ie: print "NZBID:"
the 3rd Array should split each variable from ;
assign those 12 values to the newly created array
ie: var nzbidValue = array2[0]; which would echo like:
document.write(nzbValue); // ie: print "444027"
so using both arrays I can display a listing of the posts returned..
in a nice usable format..
nzbid: 444027 // this will be used for direct download
nzbName: the name of the nzb
etc..etc..
the function i have been working on is below:
function breakNzbUrlResponse(text)
{
var place = new Array;
var place2 =new Array;
var place3 =new Array;
place[0] = text.indexOf('|');
place2[0] = text.indexOf(':');
place3[0] = text.indexOf(';');
var i = 1;
while(place[i-1] > 0 || i==1) {
place[i] = text.indexOf('|',place[i-1]+1);
place2[i] = text.indexOf(':',place2[i-1]+1);
if(place2[i] == -1)
{
place2[i] = text.length;
}
i++;
}
i=1;
var vars = new Array;
var values = new Array;
var retarray = new Array;
vars[0] = text.substr(0,place[0]);
values[0] = text.substr((place[0]+1),((place2[0]-place[0])-1));
retarray[vars[0]] = values[0];
while(i < (place.length-1) || i==1)
{
vars[i] = text.substr((place2[i-1]+1),((place[i]-place2[i-1])-1));
values[i] = text.substr((place[i]+1),((place2[i]-place[i])-1));
//alert('in loop\r\nvars['+i+'] is: '+vars[i]+'\r\nvalues['+i+'] is: '+values[i]);
retarray[vars[i]] = values[i];
i++;
}
return retarray;
}
This feels and looks like a very long winded process for this type..
all I want to do is basically assign a new variable to each return type
ie
var nzbid = array3[0];
which when split would reference the first line of the return string, NZBID:444027; where the value for NZBID would be 44027..
bit of a book going on, but the more info the better i suppose.
Thanks
Marty
You could probably cut out a significant number of lines of code by further utilizing split() instead of the manual dissections of the entries and using multidimensional arrays instead of repeatedly creating new arrays.
The logic would be:
ResultsArray = split by "|"
FieldArray = Each element of FieldArray split by ";"
ValueArray = Each element of FieldArray split by ":"
2 years later, it's sad that NZBMatrix is still using this horrible format. Here is how you can parse it.
//used to hold temporary key/value pairs
var tempKV = {};
//used to hold the search results
this.searchResults = [];
//The unformatted search results arrive in inResponse
//Remove whitespace and newlines from the input
inResponse = inResponse.replace(/(\r\n|\n|\r)/gm,"");
//search entries are delimited by |
var results = inResponse.split("|");
for(var i = 0; i < results.length; i++){
//key:value pairs in each search result are dlimited by ;
var pair = results[i].split(";");
for(var j = 0; j < pair.length; j++){
//keys and values are delimited by :
var kv = pair[j].split(":");
//normal key:value pairs have a length of 2
if(kv.length == 2){
//make sure these are treated as strings
//tempKV["key"] = "value"
tempKV["" + kv[0]] = "" + kv[1];
}
//Else we are parsing an entry like "http://" where there are multiple :'s
else if(kv.length > 2){
//store the first chunk of the value
var val = "" + kv[1];
//loop through remaining chunks of the value
for(var z = 2; z < kv.length; z++){
//append ':' plus the next value chunk
val += ":" + kv[z];
}
//store the key and the constructed value
tempKV["" + kv[0]] = val;
}
}
//add the final tempKV array to the searchResults object so long
//as it seems to be valid and has the NZBNAME field
if(tempKV.NZBNAME){
this.searchResults[i] = tempKV;
}
//reset the temporary key:value array
tempKV = {};
}
//all done, this.searchResults contains the json search results

Categories

Resources