How can I treat an imported value like an array? - javascript

I'm trying to generate a google form that has a few hundred options in a drop down.
I have all the name values in a single cell formatted as follows:
'user1','user2','user3'
It is set as in the code as follows:
var studentNames = SpreadsheetApp.openById('REDACTED').getSheetByName('Student List').getRange(3,3).getValues();
When I use this variable as shown below it treats it all as a singe value instead of an array.
.setChoiceValues([studentNames])
Any help in where to go from here?

is it a string of words with single quotes and a comma to separate them? if so, you can just do a split on the comma
var s = data
var arr = s.split(",");
and now you will have an array of strings. not sure if this answers your question.

Thanks everyone for getting me pointed in the right direction.
Turns out split was just part of the answer, I had to turn it into a string first.
.toString().split(",");

getValues() returns an object, so you need to interact with it to get the string of values for your array.
Given you are selecting just one cell and so don't need to iterate through the object, try something like this:
var studentNamesObj = SpreadsheetApp.openById('REDACTED').getSheetByName('Student List').getRange(3,3).getValues();
var studentNames = studentNamesObj[0][0].split(",");

Related

Is there a way to add each value to the first one in the for loop in JS? [duplicate]

This question already has answers here:
Easy way to turn JavaScript array into comma-separated list?
(22 answers)
Closed 2 years ago.
I have 4 different values, when looping through an array. Is it possible to add the values together like you would in Java's StringBuilder append?
I want something like this when doing a console.log():
28.0334307,-25.872523799999996, 28.031527552564445,-25.87632233243363
Now I am just getting it one for one like this when doing a console.log():
28.0334307
-25.872523799999996
28.031527552564445
-25.87632233243363
Here is my code:
var coordinates = [28.0334307, -25.872523799999996, 28.031527552564445, -25.87632233243363]
for(var item in coordinates)
{
console.log(item);
}
you can get a string in-line separated by a comma with join() method, try this:
var coordinates = [28.0334307, -25.872523799999996, 28.031527552564445, -25.87632233243363]
console.log(coordinates.join(', '));
Try this:
var coordinates = [28.0334307, -25.872523799999996, 28.031527552564445, -25.87632233243363]
console.log(coordinates.join(' '));
var coordinates = [28.0334307, -25.872523799999996, 28.031527552564445, -25.87632233243363]
console.log(coordinates.join(' '));
The browser consoles displays an array like that in to be more readable. It's not an actual structural representation of how an array is. What you want is basically a string created by joining the elements of the array.
Array.join method can be used for this:
coordinates.join("'")
Use JavaScript array join() method to display values separated by comma.
The join() method returns the array as a string.
The elements will be separated by a specified separator. The default separator is a comma (,).

Counting a particular word in a string using Zapier code

I use Zapier to automate many of our business functions, which is great, but I got stuck trying to count the number of arrays or, if you like, a particular word pattern that comes from a string. I can tidy up the string with Zapier formatter, but cannot figure out how to carry out a count.
Here is an example of a tidied string where " have been removed:
[{Name:Jon,Surname:Smith},{Name:David,Surname:Michael},{Name:Sam,Surname:Fields},{Name:Katy,Surname:Milnes}]
In this instance I would want the count on say "Name" to return 4.
I have looked at different code examples for counting words but cannot execute them correctly in the code action of Zapier. This is probably really straight forward but I do not come from a coding background so a simple Java (or Python) script to drop into the Zapier code action or some pointers on how to solve this would be greatly appreciated.
Thanks
What are you really trying to achieve by trying to count the word?
Do you just want to know the number of objects the array contains? If that is the case something like this would work. Assuming that the array is in your inputData for the code step.
var data = JSON.stringify([{'Name':'Jon', 'Surname':'Smith'},{'Name':'David','Surname':'Michael'},{'Name':'Sam','Surname':'Fields'},{'Name':'Katy','Surname':'Milnes'}]);
var inputData = {objArr: data};
// Do not insert the above lines in your code step.
// Set the objArr to your array in the inputData step.
var parsedObjArr = JSON.parse(inputData.objArr);
// Skip the above step if the array is not in the inputData object.
var arrLen = parsedObjArr.length
console.log('Array Length: ', arrLen);
// The line below outputs data from the code step.
output = {arrLen}
Also note, you do not need to remove the quotes from the JSON string.
If the array is not in the inputData of the code step, you can just directly use the length method on the array.
Well in Python you can convert the json string into dictionary with key as the name. Length of dictionary is what you are looking for. Here is the example:
import json
from collections import defaultdict
d=defaultdict(list)
x=json.dumps([{'Name':'Jon', 'Surname':'Smith'},{'Name':'David','Surname':'Michael'},{'Name':'Sam','Surname':'Fields'},{'Name':'Katy','Surname':'Milnes'}])
json_string=json.loads(x)
for obj in json_string:
if(obj['Name'] in d):
d[obj['Name']].append([obj['Name']+' '+obj['Surname']])
else:
d[obj['Name']]=[obj['Name']+' '+obj['Surname']]
print(len(d))

converting a string of comma seperated values to a multidimensional javascript array?

In my getOptions.jsp file, I have created a string with jstl.
<c:set var="options" value="Maximize,Redo,RemoveFormat,Save" />
This string should now be transformed into this format (which is, if I am correct, a multidimensional javascript array (or is it json?)).
[['Maximize', 'Redo','RemoveFormat','Save']]
I have to do this because this format is expected by a javascript method located in another .jsp (showToolbar.jsp),
function handleToolbar(options) {
//toolbar = [['Maximize', 'Redo','RemoveFormat','Save']]; the expected format!
toolbar = options;
}
So my question is, how do I transform the comma-seperated string 'options' into the format that is expected in the 'toolbar' variable in order to pass it from one jsp to the other and pass it as a parameter of the handleToolbar function.
Note: I guess it is not ideal to use javascript in a jsp but that I cannot change because I inherited the code.
Thanks alot in advance, I've been searching for hours for the solution and can't find it.
Simple:
var myString = "Maximize,Redo,RemoveFormat,Save";
var myArray = [myString.split(',')];
The result is an array that has 1 element in it. That 1 element is this array:
['Maximize', 'Redo','RemoveFormat','Save']
So, myArray is:
[['Maximize', 'Redo','RemoveFormat','Save']]

How do I use #DbLookup results to populate a Readers field in xpages?

db = new Array("myserver", "myfolder\\mydb.nsf")
dir = getComponent("Dir").value;
div = getComponent("Div").value;
lu = #DbLookup(db, "ManagerAccess", dir + "PP" + div, "DTManagers");
var a = [];
a.push(lu);
var item:NotesItem = docBackEnd.replaceItemValue('FormReaders', #Unique(a));
item.setReaders(true);
That code is on the querySaveDocument ssjs. The result I get from the #DbLookup (when I put in a computed field) look like this:
Pedro Martinez,Manny Ramirez,David Ortiz,Terry Francona
I tried doing an #Explode(#Implode) thing on it, but it doesn't seem to work.
The error I get in the browser just tells me that the replaceItemValue line is broken.
To test it, I pushed several strings one at a time, and it worked correctly populating my FormReaders field with the multiple entries.
What am I doing wrong?
I see several problems here:
A. In cases as described by you #Dblookup in fact would return an array. If you push an array into a plain computedField control it will exactly look as that you wrote:
value1, value2, ..., valueN
A computedField doesn't know anything about multiple values etc, it just can display strings, or data that can be converted to strings.
If you want to test the return value you could try to return something like lu[0]; you then should receive the array's 1st element, or a runtime error, if lu is NOT an array. Or you could ask for the array's size using lu.length. That returns the number of array elements, or the number of characters if it's just a plain string.
B. your code contains these two lines:
var a = [];
a.push(lu);
By that you create an empty array, then push lu[] to the first element of a[]. The result is something like this:
a[0] = [value1, value2, ..., valueN],
i.e. a is an array where the first element contains another array. Since you don't want that, just use #Unique(lu) in your replaceItemValue-method.
C. I don't see why replaceItemValue would throw an error here, apart from what I wrote in topic B. Give it a try by writing lu directly to the item (first without #Unique). That should work.
D. for completeness: in the first line you used "new Array". A much better way to define your db parameters is
var db = ["myserver", "myfolder/mydb.nsf"];
(see Tim Tripcony's comment in your recent question, or see his blog entry at http://www.timtripcony.com/blog.nsf/d6plinks/TTRY-9AN5ZK)

Retrieve JSON Array element value

My web service returned a JSON Array (ie. [{"key":"value"}, {"key":"value2"}]). In the array there are two items as you can see, which are separated with comma. I want to know how can I access the second item, and get the value of "key" for the second item.
I've tried:
var a = msg.d[1].key
With no success of course.
This is the returned string:
"[{"Code":"000000","Name":"Black","Id":9},{"Code":"BF2C2C","Name":"Red","Id":11}]"
The string was extracted using FireBug after watching the msg.d.
Need your help in solving this.
msg[1].key
Assuming that the name of that array is msg. I'm not sure what you are using .d for.
If msg.d is a string representing an array, use JSON.parse.
JSON.parse(msg.d)[1].key
You can replace key with the key you are wanting, e.g. Code, Name, Id, etc.
This works as expected for me.
var msg = [{"key":"value"}, {"key":"value2"}];
var a = msg[1].key;
What is msg in the example above? Need more info to help.
If msg.d is a string then you have to eval (uggh) or parse it before applying the array subscript.

Categories