Javascript/Google Apps Script IndexOf issues [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 months ago.
Improve this question
There are a couple of similar queries here about the IndexOf function, but I'm reaching out because although the answers provided have been helpful, none of them have solved the issue.
I have a (very) large 2d array from a spreadsheet of names vs id codes. I read these values in apps script into an array (rIdr in the snippet below).
I then build 2x one-dimensional arrays so that I can use IndexOf to search for a name in the first array then use the returned index it to pull out the value from the second array.
var keys=[]; var vals=[];
//build key-val lookup arrays
for (var i = 0; i < rIdr.values.length; i++){
var k = rIdr.values[i][0].toString()
keys[i]=k
var v = rIdr.values[i][1].toString()
vals[i]=k
}
The name I'm looking for is obtained from a JSON which is populated elsewhere. I iterate over the names in this object, looking for them in my key and val arrays:
jsonobj.data.forEach(function(value) {
var idx = keys.indexOf(value.first_names_txt + " " + value.last_name_txt)
var id = -1;
if (idx > -1){id = vals[idx]}
Logger.log(value.first_names_txt + " " + value.last_name_txt + " " + id)
});
I've verified that both the name i'm pulling out of the JSON object as well as the elements of the keys array are String types. I've seen in the object inspector that the keys array is an array of strings (not, for example, an array of array objects).
Try as I might, i can't get IndexOf to return anything other than -1.
Even if I explicitly look for a name which I know is in there (and actually is a copy paste of the name as it's written on the sheet that I'm pulling values from), I still get -1 returned
var test
test = keys.indexOf("Joe Bloggs")
I'm tearing my hair out here. I don't want to write a separate function to match a name in the keys array, because I'll either need to pass in the full keys array as an argument, or make it a global variable - neither of which i want to do for various reasons.
Can anyone help with why IndexOf doesn't work here?
And if this is an issue that won't go away, is there a way to write my own search function which avoids passing large arrays around or declaring them as global variables?
Thanks all in advance

Description
I've constructed a spreadsheet sheet using the names from the json data file, randomized the names so they are no longer in alphabetical order and then assigned an id number to each.
The sample script I've provided lists the id number for the names in the json data file. Notice I'm working with the original data array. I don't need to create key value arrays to get the result I want. And I'm not checking if a name doesn't exist in the data array.
I've truncatd the json data for brevity
Code.gs
function test_json() {
try {
let jdata = {
"type" : "entrants",
"data" : [ {
"type" : "entrant",
"id" : "en_tdgwjajthr",
"first_names_txt" : "Archie",
"last_name_txt" : "White",
"entrytype" : "et_dv8u152j",
"answers" : {
"q_wg5qq6bgvsy90rh" : "Partenza Nude-Espresso RT"
}
}, {
.
.
.
.
}, {
"type" : "entrant",
"id" : "en_8uhauoe3jo",
"first_names_txt" : "Valentijn",
"last_name_txt" : "Brax",
"entrytype" : "et_dv8u152j",
"answers" : {
"q_wg5qq6bgvsy90rh" : "Dulwich Paragon CC"
}
} ],
"has_more_bool" : false
};
let values = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test").getDataRange().getValues();
jdata.data.forEach(function(value){
let key = value.first_names_txt+" "+value.last_name_txt;
let found = values.find( row => row[0] === key );
console.log("key = "+key+" id = "+found[1]);
});
}
catch(err) {
console.log(err)
}
}
Execution log (abbreviated)
10:29:05 AM Notice Execution started
10:29:06 AM Info key = Archie White id = 21
10:29:06 AM Info key = ari panzer id = 15
10:29:06 AM Info key = Daniel Mulcahy id = 5
10:29:06 AM Info key = David Streule id = 12
10:29:06 AM Info key = Dominic Bell id = 10
10:29:06 AM Info key = Euan Davies id = 14

Related

Extract specific nested array in JSON Objects that match data with Javascript

I'm working with an NBA API where one of the features is finding players by their last name.
The issue I have; is that multiple players can have the same last name, of course.
An example of the response from the API when sorting with last names:
"players": [
0: {
"firstName":"Anthony"
"lastName":"Davis"
"teamId":"17"
"yearsPro":"9"
"collegeName":"Kentucky"
"country":"USA"
"playerId":"126"
"dateOfBirth":"1993-03-11"
"affiliation":"Kentucky/USA"
"startNba":"2012"
"heightInMeters":"2.08"
"weightInKilograms":"114.8"
1: {
"firstName":"Deyonta"
"lastName":"Davis"
"teamId":"14"
"yearsPro":"3"
"collegeName":"Michigan State"
"country":"USA"
"playerId":"127"
"dateOfBirth":"1996-12-02"
"affiliation":"Michigan State/USA"
"startNba":"2016"
"heightInMeters":"2.11"
"weightInKilograms":"107.5"
}
I limited the results here, but it goes on and on, etc.
So, I am looking to do two things:
First, extract/filter the correct player using their first name and last name.
In said extraction, I still need the complete array information when it is matched.
So essentially, I want 'Deyonta Davis', but when found - I also need the rest of said player's information (years pro, college, country, etc.)
I already have a command set up to retrieve the first result of the nested data in this API via last name - where the command takes the last name you input and sends the first result. The precise problem is that the first result is likely not to be the guy you are looking for.
The goal is to include first & last name to avoid pulling the wrong player.
A snippet of how I currently call the information via last name:
// Calling API
const splitmsg = message.content.split(' ')
var lastnameurl = "https://api-nba-v1.p.rapidapi.com/players/lastName/" + splitmsg[1];
axios.get(lastnameurl, {
headers: {
"x-rapidapi-key": apikey,
"x-rapidapi-host": apihost
}
// Extracting Player Information (first result)
var playerfirstname = response.data.api.players[0].firstName;
var playerlastname = response.data.api.players[0].lastName;
var collegename = response.data.api.players[0].collegeName;
var countryname = response.data.api.players[0].country;
var playerDOB = response.data.api.players[0].dateOfBirth;
var yrspro = response.data.api.players[0].yearsPro;
var startednba = response.data.api.players[0].startNba;
Any help would be appreciated, thank you.
If I understand the question correctly the task is:
Retrieve first matching object from an array where properties firstName and lastName equal to desired values.
To achieve this you could use build in find function.
const player = array.find(el => {
return el.firstName === "Deyonta" && el.lastName === "Davis"
});
Keep in mind if there is no such object in array the player will be undefined.

Remove element from named values in javascript

I have the following function, which is called when a google forms is submitted. I'm trying to concatenate all answers into a single array that's gonna be used latter:
function onFormSubmit(e) {
var respostas = e.namedValues;
for(item in respostas){
rp = rp.concat(respostas[item]);
}
}
But I would like to drop the timestamp that comes together with the answers. I can access it with respostas['Timestamp'], but I can't find a way to drop or ignore it. The documentation didn't help much.
var cp = [];
function onSubmitForm(e) {
var respostas = e.namedValues;
for (var name in respostas) {
if (respostas.hasOwnProperty(name) {
if (name !== 'Timestamp') {
cp.push(respostash[name]);
}
}
}
}
This is what I would suggest. Using concat to add an item is overkill, you can just push it. Also is a good practice when you are looping over object properties to make sure that they are its own properties of that object, not inherited from prototype. You can read more about it here
You can check the name of the property before concatenate it with the rest.
If the key item equals Timestamp (the undesired property) just skip the current loop.
for(item in respostas) {
if (item === 'Timestamp') {
continue;
}
rp = rp.concat(respostas[item]);
}
EDIT: Based on comments, OP attests that item in the for..in loop is a integer, but, unless his/her code differs radically from the docs, the variable should hold strings, not numbers.
var respostas = {
'First Name': ['Jane'],
'Timestamp': ['6/7/2015 20:54:13'],
'Last Name': ['Doe']
};
for(item in respostas) {
console.log(item);
}
e.namedValues returns a JSON Object with custom keys.
var jsonObj = e.namesValues;
/* e.namedValues returns data like this...
{
"test1": "testval1",
"test2": "testval2",
"test3": "testval3",
}
*/
for(item in respostas){
Logger.log(item); //Key
Logger.log(respostas[item]); //Value
}
This should let you access the key or value on the items in respostas.
The accepted answer is better as it does more to help the user to fix their exact problem, however, I will leave this here for future users in case they want to understand how to access the variables in the object that Google Apps Scripts returns.

node red array / how to "use" specific place

in node red i collect values with "Collector" the collector sends me an "Object" with all pairs of values when one of them is updated:
{ "mqtt/1/": "-127.00", "mqtt/0/": "41.94" }
with "json" and after with "stringsplit" i got an array of f.e. 9 values:
array [9] (can be up to 80 pairs of values)!
[ "{", "mqtt/1/", ":", "-127.00", ",", "mqtt/0/", ":", "41.61", "}" ]
now i want to have a function node which compares the Value (-127.00) from the Topic (mqtt/1/) with the Value (41.61) from the Topic (mqtt/0/).
this i working ...BUT only if i know which is the first topic/value and which is the second...
var outputMsgs = msg.payload;
var top1=outputMsgs[1];
var val1=outputMsgs[3];
var top2=outputMsgs[5];
var val2=outputMsgs[7];
msg = {payload: val1}
var msg2 = {payload: val2}
if (val1>val2)
{var msgOUT={payload: "BIGGER"};}
return [msg, msg2, msgOUT];
But the Problem is, that sometimes "mqtt/1/" comes first, sometimes "mqtt/0/" and values will be switched. So now, maybe somebody can help to write a function to pick the right value with the right topic to compare them in the next step.
Maybe is there a Way to look if the topic contains 0, 1 ...80, and then save it in this order in a array???
Thank you in advance!
If the initial msg.payload is truly a javascript object as you describe, ie:
msg.payload = { "mqtt/1/": "-127.00", "mqtt/0/": "41.94" }
then you can reference the two values as:
var value1 = msg.payload["mqtt/1/"];
var value1 = msg.payload["mqtt/2/"];
If msg.payload is actual a JSON string, then pass the message through a JSON node first to convert it to the object.
There is no need to try splitting the string yourself and parsing the content.

Loop through all Mongo collections and execute query

First of, I'm quite new to mongodb. Here's my question I've not been able to find a solution to.
Let's say I have 3 different collections.
mongos> show collections
collectionA
collectionB
collectionC
I want to create a script that iterates over all collections ind this database and find the last inserted timestamp in each of these collections. Here's what works inside mongos.
var last_element = db.collectionA.find().sort({_id:-1}).limit(1);
printjson(last_element.next()._id.getTimestamp());
ISODate("2014-08-28T06:45:47Z")
1. Problem (Iterate over all collections)
Is there any possibility to to sth. like.
var my_collections = show collections;
my_collections.forEach(function(current_collection){
print(current_collection);
});
Problem here, the assignment for my_collections does not work.
I get SyntaxError: Unexpected identifier. Do I need to quote the 'show' statement ? Is it even possible ?
2. Problem (storing collection in js var)
I can workaround Problem 1 by doing this:
var my_collections = ["collectionA", "collectionB", "collectionC"];
my_collections.forEach(function(current_collection){
var last_element = db.current_collection.find().sort({_id:-1}).limit(1);
print(current_collection);
printjson(last_element.next()._id.getTimestamp());
});
The last_element.next() produces the following error:
error hasNext: false at src/mongo/shell/query.js:124
It seems that last_element isn't saved correctly.
Any suggestions on what I'm doing wrong??
UPDATE
Neils answer lead me to this solution. In addition to his code I had to check if the function getTimestamp really exist. For some 'virtual' collections there seem to be no _id property.
db.getCollectionNames().forEach(function(collname) {
var last_element = db[collname].find().sort({_id:-1}).limit(1);
if(last_element.hasNext()){
var next = last_element.next();
if(next._id !== undefined && typeof next._id.getTimestamp == 'function'){
printjson(collname + " >> "+next._id.getTimestamp());
}else{
print(collname + " undefined!! (getTimestamp N/A)")
}
}
});
There is the db.getCollectionNames() helper method that does this for you. You can then implement your code:
db.getCollectionNames().forEach(function(collname) {
// find the last item in a collection
var last_element = db[collname].find().sort({_id:-1}).limit(1);
// check that it's not empty
if (last_element.hasNext()) {
// print its timestamp
printjson(last_element.next()._id.getTimestamp());
}
})
You probably also want a .hasNext() check in there to cater for possible empty collections.
Rename the collection name present in all the records using the following script:
db = db.getSiblingDB("admin");
dbs = db.runCommand({ "listDatabases": 1 }).databases;
dbs.forEach(function(database) {
db = db.getSiblingDB(database.name);
db.currentname.renameCollection("newname");
});

Looping to Parse JSON Data

Description and Goal:
Essentially data is constantly generated every 2 minutes into JSON data. What I need to do is retrieve the information from the supplied JSON data. The data will changed constantly. Once the information is parsed it needs to be captured into variables that can be used in other functions.
What I am stuck in is trying to figure out how to create a function with a loop that reassigns all of the data to stored variables that can later be used in functions.
Example information:
var json = {"data":
{"shop":[
{
"carID":"7",
"Garage":"7",
"Mechanic":"Michael Jamison",
"notificationsType":"repair",
"notificationsDesc":"Blown Head gasket and two rail mounts",
"notificationsDate":07/22/2011,
"notificationsTime":"00:02:18"
},
{
"CarID":"8",
"Garage":"7",
"Mechanic":"Tom Bennett",
"notificationsType":"event",
"notifications":"blown engine, 2 tires, and safety inspection",
"notificationsDate":"16 April 2008",
"notificationsTime":"08:26:24"
}
]
}};
function GetInformationToReassign(){
var i;
for(i=0; i<json.data.shop.length; i++)
{
//Then the data is looped, stored into multi-dimensional arrays that can be indexed.
}
}
So the ending result needs to be like this:
shop[0]={7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18 }
shop[1]={}
You can loop through your JSON string using the following code,
var JSONstring=[{"key1":"value1","key2":"value2"},{"key3":"value3"}];
for(var i=0;i<JSONstring.length;i++){
var obj = JSONstring[i];
for(var key in obj){
var attrName = key;
var attrValue = obj[key];
//based on the result create as you need
}
}
Hope this helps...
It sounds to me like you want to extract the data in the "shop" property of the JSON object so that you can easily reference all of the shop's items. Here is an example:
var json =
{
"data":
{"shop":
[
{"itemName":"car", "price":30000},
{"itemName":"wheel", "price":500}
]
}
},
inventory = [];
// Map the shop's inventory to our inventory array.
for (var i = 0, j = json.data.shop.length; i < j; i += 1) {
inventory[i] = json.data.shop[i];
}
// Example of using our inventory array
console.log( inventory[0].itemName + " has a price of $" + inventory[0].price);
Well, your output example is not possible. You have what is a list of things, but you're using object syntax.
What would instead make sense if you really want those items in a list format instead of key-value pairs would be this:
shop[0]=[7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18]
For looping through properties in an object you can use something like this:
var properties = Array();
for (var propertyName in theObject) {
// Check if it’s NOT a function
if (!(theObject[propertyName] instanceof Function)) {
properties.push(propertyName);
}
}
Honestly though, I'm not really sure why you'd want to put it in a different format. The json data already is about as good as it gets, you can do shop[0]["carID"] to get the data in that field.

Categories