In the application a csv or xlsx file is parsed and the user then selects which fields represent an address.
After that I put the entire csv into an array and start to loop through it to send the address to be geocoded. The issue that I am having is that I need a way to set the array element equal to the field the user selected.
Before I loop through the array I grab the selection from each of the dropdowns like so.
var address_selection = document.getElementsByName("address1")[0].value;
var address2_selection = document.getElementsByName("address2")[0].value;
var city_selection = document.getElementsByName("city")[0].value;
var state_selection = document.getElementsByName("state")[0].value;
var postalcode_selection = document.getElementsByName("postalcode")[0].value;
My current code is setup like this, which hard codes the variable equal to a specific element.
for (i = 0; i < output.length; i++) {
var id = output.ID;
var address = output[i].Address;
var address2 = output[i].Address2;
var city = output[i].City;
var state = output[i].StateProvince;
var postalcode = output[i].ZipPostalcode;
What I need to do is somehow keep the variable names the same but change the element based on the user selection. I have tried something like this but it does not work.
var address = ("output[i]." + address_selection);
You can reference array indexes and object properties using [] notation, so in JS, this is very easy.
In your case, it looks like output is an array of objects, so output[i] is an object with fields like Address, Address2 etc. Instead of writing output[i].Address you can write it as output[i]["Address"]. Furthermore, "Address" can be replaced with a variable just like i.
With that in mind, and assuming the values of the options in your dropdownlists are things like "Address" and "Address2" then you should just be able to write this:
var address_selection = document.getElementsByName("address1")[0].value;
var address2_selection = document.getElementsByName("address2")[0].value;
var city_selection = document.getElementsByName("city")[0].value;
var state_selection = document.getElementsByName("state")[0].value;
var postalcode_selection = document.getElementsByName("postalcode")[0].value;
for (i = 0; i < output.length; i++) {
var id = output.ID;
var address = output[i][address_selection];
var address2 = output[i][address2_selection];
var city = output[i][city_selection];
var state = output[i][state_selection];
var postalcode = output[i][postalcode_selection];
var address_selection = document.getElementsByName("address1")[0].value;
var address2_selection = document.getElementsByName("address2")[0].value;
var city_selection = document.getElementsByName("city")[0].value;
var state_selection = document.getElementsByName("state")[0].value;
var postalcode_selection = document.getElementsByName("postalcode")[0].value;
var myArray = {
address_selection: address_selection,
address2_selection: address2_selection,
city_selection: city_selection,
state_selection: state_selection,
postalcode_selection: postalcode_selection
};
for (var key in myArray) {
console.log("key " + key + " has value " + myArray[key]);
}
Related
I am trying to automate the process of parsing data in one of my columns. So far I have it so that after applying a formula I get the data I need but with text around it.
I would like to find and replace the cell values such that I only have the data that is in quotations marks without the quotations. How would I do this via script? Refer to the picture below. This is what I have so far:
var src = ":utm_source=>";
var med = ":utm_medium=>";
var camp = ":utm_campaign=>";
var term = ":utm_term=>";
var con = ":utm_content=>";
var r1 = "";
var data = sheet.getDataRange().getValues();
Logger.log(data.length);
for (var i = 0; i < data[0].length;i++){
for (var j = 0; j < data.length;j++){
Logger.log(data[j][i]);
if(data[j][i].indexOf(src) > -1 || data[j][i].indexOf(med) > -1 || data[j][i].indexOf(camp) > -1 || data[j][i].indexOf(term) > -1 || data[j][i].indexOf(con) > -1){
sheet.getRange(j+1,i+1).setValue(r1);
sheet
}
}
}
Use split('"')[1] (see split()) to retrieve the substring between the quotations.
As a best practice, modify the 2D array you retrieved (data) and use setValues(data), instead of setting every individual with setValue. One way to do that it through a combination of map() and some(), as can be seen below (check inline comments):
var src = ":utm_source=>";
var med = ":utm_medium=>";
var camp = ":utm_campaign=>";
var term = ":utm_term=>";
var con = ":utm_content=>";
var starters = [src,med,camp,term,con]; // Put all starters to check in an array
var range = sheet.getDataRange();
var data = range.getValues();
data = data.map(row => row.map(value => { // Iterate through all rows and cells
var includesStarter = starters.some(starter => value.includes(starter)); // Check if cell value includes a starter
if (includesStarter) return value.split('"')[1]; // Retrieve value within quotations
else return value; // If starter is not included in cell, don't change the array
}));
range.setValues(data); // Write modified data to original range
I've searched high and wide for an answer but can't seem to find it. I am trying to alter my custom function that looks up sitemap URL's and the date they were updated to accept a range of inputs.
Here is the current function that works:
function sitemap(sitemapUrl, namespace) {
var array = [];
var xml = UrlFetchApp.fetch(sitemapUrl).getContentText();
var document = XmlService.parse(xml);
var root = document.getRootElement();
var sitemapNameSpace = XmlService.getNamespace("http://www.sitemaps.org/schemas/sitemap/0.9");
var urls = root.getChildren('url', sitemapNameSpace);
for (var i = 0; i < urls.length; i++) {
var loc = urls[i].getChild('loc', sitemapNameSpace).getText();
var lastmod = urls[i].getChild('lastmod', sitemapNameSpace).getText();
array.push([loc, lastmod]);
}
return array;
}
I've tried using Google's example below but doesn't seem to work however I incorporate it into my function. Any ideas?
function DOUBLE(input) {
if (input.map) { // Test whether input is an array.
return input.map(DOUBLE); // Recurse over array if so.
} else {
return input * 2;
}
}
Edit: This is how I tried to use Google's example for my function:
function sitemaps(sitemapUrl) {
var array = [];
var xml = UrlFetchApp.fetch(sitemapUrl).getContentText();
var document = XmlService.parse(xml);
var root = document.getRootElement()
var sitemapNameSpace = XmlService.getNamespace("http://www.sitemaps.org/schemas/sitemap/0.9")
var urls = root.getChildren('url', sitemapNameSpace)
for (var i = 0; i < urls.length; i++) {
var loc = urls[i].getChild('loc',sitemapNameSpace).getText();
var lastmod = urls[i].getChild('lastmod',sitemapNameSpace).getText();
array.push([loc, lastmod]);
}
if (sitemapUrl.map) {
return sitemapUrl.map(sitemaps);
} else {
return array
}
You are no using the same format as the Google example. As of right now you are checking if the input is an array after actually retrieving the data.
But you using fetch with an array as input could trigger an Error and the function may no get to the point where it checks if the sitemapUrl can be used with map.
Also take into account that map will call the function in every single element of the array and return an array with a result for each of element. So in your case B3:B6 would call the function for the value at B3, B4, B5 and B6 and return an array of length 4 with the result. For your case in which you want a single list you need to flattern the array afterwards
I would change your function to be like this:
function sitemaps(sitemapUrl) {
if (sitemapUrl.map) {
return sitemapUrl.map(sitemaps).flat();
} else {
var array = [];
var xml = UrlFetchApp.fetch(sitemapUrl).getContentText();
var document = XmlService.parse(xml);
var root = document.getRootElement()
var sitemapNameSpace = XmlService.getNamespace("http://www.sitemaps.org/schemas/sitemap/0.9")
var urls = root.getChildren('url', sitemapNameSpace)
for (var i = 0; i < urls.length; i++) {
var loc = urls[i].getChild('loc', sitemapNameSpace).getText();
var lastmod = urls[i].getChild('lastmod', sitemapNameSpace).getText();
array.push([loc, lastmod]);
}
return array
}
}
Although what you are doing is fine take into account that it also exists a way to retrieve all the request at the same time (
UrlFetchApp.fetch()) but for this specific case you would need to flatten a reshape the input array.
EDIT - code to calculate refill_playlist_len included
I have a function in Javascript that deletes a row of an HTML table and populates it again with values from arrays.
Within this deleteRow function, I have a for loop which loops through a string and assigns parts of the strings to different variables and tries to push them onto arrays.
Without the for loop, it works fine (i.e. when I just index manually) but for some reason when I place it in a for loop, the values aren't pushed onto the arrays. The values themselves print fine on each iteration they just aren't added to the array.
Refill_playlist_len is the count of the Django Queryset (30).
var refill_playlist_len = '{{ playlist.count }}';
var artist_Arr = [];
var track_Arr = [];
var track_id_Arr = [];
var album_Arr = [];
var artist_name;
var track_name;
var track_id;
var album_name;
for (var i = 0; i < refill_playlist_len; i++) {
var searchStr = refill_playlist[i];
console.log(searchStr);
console.log(typeof searchStr);
console.log(typeof refill_playlist);
//grab variables
artist_name = searchStr.match(new RegExp("artist_name:" + "(.*)" + ", album_name:"));
console.log(artist_name[1]);
artist_Arr.push(artist_name[1]);
track_name = searchStr.match(new RegExp("track_name:" + "(.*)" + ", acousticness:"));
console.log(track_name[1]);
track_Arr.push(track_name[1]);
track_id = searchStr.match(new RegExp("track_id:" + "(.*)" + ", track_name:"));
console.log(track_id[1]);
track_id_Arr.push(track_id[1]);
album_name = searchStr.match(new RegExp("album_name:" + "(.*)" + ", track_number:"));
console.log(album_name[1]);
album_Arr.push(album_name[1]);
}
The console logs are in the image below. You can see part of the 'searchStr' printed, along with the data types, artist name, track IDs, etc but for some reason, it says that 'searchStr' is undefined?
Console
I'm quite new to Javascript so my apologies if there is something basic I'm forgetting.
Multiple issues with code. Please clean up code. Sample is given below.
function find(refill_playlist) {
const refill_playlist_len = refill_playlist.length
let artist_Arr = []
let track_id_Arr = []
let track_Arr = []
let album_Arr = []
for (i = 0; i < refill_playlist_len; i++) {
var searchStr = refill_playlist[i];
if(!searchStr) continue;
//grab variables
artist_name = searchStr.match(/artist_name:(.*), album_name:/);
artist_name && artist_Arr.push(artist_name[1]);
track_name = searchStr.match(/track_name:(.*), acousticness:/);
track_name && track_Arr.push(track_name[1]);
track_id = searchStr.match(/track_id:(.*), track_name:/);
track_id && track_id_Arr.push(track_id[1]);
album_name = searchStr.match(/album_name:(.*), track_number:/);
album_name && album_Arr.push(album_name[1]);
}
console.log(artist_Arr)
console.log(track_id_Arr)
console.log(track_Arr)
console.log(album_Arr)
}
find(
[
`
artist_name: test, album_name:
`,
null
]
)
Instead of "var instance = ..." adding the two values it concatenates them. Can anyone suggest what I need to fix?
I'm trying to add "var startingEmail" value and "var k".
Thank you for your help!
var startingEmail = sheet.getRange("C2").getDisplayValue();
var numEmails = sheet.getRange("E2").getDisplayValue();
var max = numEmails;
for (var k = 0; k<max; ++k){
var threads = GmailApp.getInboxThreads(startingEmail,max)[k]; //get max 50 threads starting at most recent thread
var messages = threads.getMessages()[0];
var sndr;
var rcpnt;
var srAry = [];
var sndr = messages.getFrom().replace(/^.+<([^>]+)>$/, "$1"); //http://stackoverflow.com/questions/26242591/is-there-a-way-to-get-the-specific-email-address-from-a-gmail-message-object-in
var sndrLower = sndr.toLowerCase;
var rcpnt = messages.getTo().replace(/^.+<([^>]+)>$/, "$1");
var rcpntLower = rcpnt.toLowerCase;
var cc = messages.getCc().replace(/^.+<([^>]+)>$/, "$1");
var ccLower = cc.toLowerCase;
//srAry.push(sndr);
//srAry.push(rcpnt);
//srAry.push(cc);
var isIn = joinAddr.search(sndr || rcpnt);
if(isIn == -1){
var instance = k;
I can't see the example in your code but it sounds like you can just wrap Number() around your variable and it will perform the type conversion so the code will perform the math instead of concatenating as strings.
i been reading for hours trying to make this work but i dont have much knowledge to do it.
I have this js code:
var username=$(this).attr("username");
It pull a list of users f.e (admin, test1, test2, test3)
and i needs to split it into another var like this:
var members = [
['admin'],
['test1'],
['test2'],
['test3'],
];
I tried a lot of codes but i cant make it work, thanks in advance!
To get an array of usernames:
var username = $(this).attr("username");
var members = username.split(',');
To get exactly what you've suggested you want (an array of arrays? - I don't think this is actually what you want):
var username = $(this).attr("username");
var membersArr = username.split(',');
var members = new Array();
for (var i = 0; i < membersArr.length; i++)
{
members[i] = [ membersArr[i] ];
}
To get "[test1]", "[test2]" etc:
var username = $(this).attr("username");
var members = username.split(',');
for (var i = 0; i < members.length; i++)
{
members[i] = '[' + members[i] + ']';
}
Update
To get the array of arrays,
var username=$(this).attr("username");
var membersArray= username.split(' ').map(function(username){
return [username];
})
//[["admin"],["test"],["test1"],["test2"]]
I've added a fiddle here