Can't convert Array to Object[][] error - javascript

I'm trying to make a simple script in google doc, but when I run it stops at line 15 with error as in the title. It works if only I remove that line. Can you help me please?
function influencer_update() {
var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Influencer');
var dzis = sheet1.getRange('O1').getValue(); //today date
var lista = sheet1.getRange('Q2:Q').getValues(); //list of values
var lista_st = sheet1.getRange('D2:D').getValues(); //list of values to update
var daty = sheet1.getRange('O2:O').getValues(); //list of dates, when value was last update
for (i in lista) {
if (lista[i]>0) {
lista_st[i]=lista[i]
daty[i] = dzis
}
}
sheet1.getRange('D2:D').setValues(lista_st);
sheet1.getRange('O2:O').setValues(daty);
Browser.msgBox('daend');
}

I believe setValues() and getValues() always uses 2d array. When you do daty[i] = dzis, it converts daty to 1d array. Hence it gives you the error message Can't convert Array to Object[][]. If you change the line
daty[i] = dzis
to
daty[i][0] = dzis
or
daty[i] = [dzis]
should fix the problem.

Related

Google Apps Script - Usage of "indexOf" method

first: I really tried hard to get along, but I am more a supporter than a programmer.
I put some Text in Google Calc and wanted to check the amount of the occurances of "Mueller, Klaus" (It appears 5 times within the data range). The sheet contains 941 rows and 1 Column ("A").
Here is my code to find out:
function countKlaus() {
// Aktives Spreadsheet auswählen
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Aktives Tabellenblatt auswählen
var sheet = ss.getSheetByName("Tabellenblatt1");
var start = 1;
var end = sheet.getLastRow();
var data = sheet.getRange(start,1,end,1).getValues();
var curRow = start;
var cntKlaus = 0;
for( x in data )
{
var value = daten[x];
//ui.alert(value);
if(value.indexOf("Mueller, Klaus")> -1){
cntKlaus = cntKlaus + 1;
}
}
ui.alert(cntKlaus);
}
The result message is "0" but should be "5".
Issues:
You are very close to the solution, except for these two issues:
daten[x] should be replaced by data[x].
ui.alert(cntKlaus) should be replaced by SpreadsheetApp.getUi().alert(cntKlaus).
Solution (optimized by me) - Recommended:
function countKlaus() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName("Tabellenblatt1");
const cntKlaus = sheet
.getRange('A1:A' + sheet.getLastRow())
.getValues()
.flat()
.filter(r=>r.includes("Mueller, Klaus"))
.length;
SpreadsheetApp.getUi().alert(cntKlaus);
}
You can leave out this term + sheet.getLastRow() since we are filtering on a non-blank value. But I think it will be faster to have less data to use filter on in the first place.
References:
flat : convert the 2D array to 1D array.
filter : filter only on "Mueller, Klaus".
Array.prototype.length: get the length of the filtered data
which is the desired result.
includes: check if Mueller, Klaus is included in the text.
Bonus info
Just for your information, my solution can be rewritten in one line of code if that's important to you:
SpreadsheetApp.getUi().alert(SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Tabellenblatt1").getRange('A1:A').getValues().flat().filter(r=>r.includes("Mueller, Klaus")).length);

How do I convert a JSON string object value to an integer?

I'm tring to convert a JSON object value to an integer and calculate.
It shows representativeRow.DTA_VAL well but the value of total shows NaN.
I don't think this works because the other code works well.
datav= Number(representativeRow.DTA_VAL);
this is my code
var rows = resp.Sttsapitbldata[1].row;
if (rows) {
var representativeRow;
for (i = 1; i < 30; i++) {
representativeRow = rows[i];
if(representativeRow.ITM_NM.substring(0,2)=="부산"){
// console.log(representativeRow.ITM_NM);
var sub =representativeRow.ITM_NM.substring(0,3);
var total;
var datav;
console.log(representativeRow.DTA_VAL);
datav= Number(representativeRow.DTA_VAL);
total+=datav;
console.log(total);
}
itemNm2 = representativeRow.ITM_NM;
dataV = representativeRow.DTA_VAL;
//console.log(itemNm2);
//console.log(dataV);
options.data.data.push({locname: itemNm2, listshrs: dataV});
}
korea = webponent.visual.korea.init($(".korea"), style, options);
}
See JSON file code below.
{"Sttsapitbldata":[{"head":[{"list_total_count":88},{"RESULT":{"CODE":"INFO-000","MESSAGE":"정상 처리되었습니다."}}]},{"row":[{"STATBL_ID":"T183673021266818","DTACYCLE_CD":"YY","WRTTIME_IDTFR_ID":"2016","ITM_ID":10001,"ITM_NM":"계","CLS_ID":50033,"CLS_NM":"강간","UI_NM":"명","DTA_VAL":5155,"DTA_SVAL":null},{"STATBL_ID":"T183673021266818","DTACYCLE_CD":"YY","WRTTIME_IDTFR_ID":"2016","ITM_ID":10002,"ITM_NM":"서울","CLS_ID":50033,"CLS_NM":"강간","UI_NM":"명","DTA_VAL":1129,"DTA_SVAL":null},{"STATBL_ID":"T183673021266818","DTACYCLE_CD":"YY","WRTTIME_IDTFR_ID":"2016","ITM_ID":10003,"ITM_NM":"부산","CLS_ID":50033,"CLS_NM":"강간","UI_NM":"명","DTA_VAL":314,"DTA_SVAL":null},
You should initialise total=0. You can't add to a null value on the first iteration. Although looking at it, I suspect you'd be wanting to initialise total outside of the loop

Get last value from an array using Google Apps Script

I need to get last value from an array and I keep getting this error when I use slice
TypeError: Cannot find function slice in object Sun Jul 23 2017 00:00:00 GMT+0100 (BST). (line 15, file
If I use length -1 I get NaN.
This is the code I am using it.
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Data");
var range = sheet.getDataRange();
var values = range.getValues();
var today = new Date(Date.now());
today.setHours(0,0,0,0);
Logger.log(today);
var setTotal;
var getToday = values[4].map(Number).indexOf(+today);
Logger.log(getToday);
for (i = 0; i < values.length; i++) {
var getTotal = values[i][getToday];
Logger.log(getTotal.slice(-1)[0]);
}
}
... and this is the table
full table
So I need when it match the current day (today) to retrieve last value from that array (column) which is the Total for that day.
Thank you!
Kind regards,
getTotal is always already a singular value.
Also the way you find your column is brittle due to timezones because you normalize only one date.
If you do it with both dates (which needs to be handled safely unless you want to do index constraints) your column finding approach works.
function getTodaysTotal() {
function toUtcMidnight(date) {
try {return date.setHours(0,0,0,0);}
catch(e) {return;}
}
var values = SpreadsheetApp
.getActiveSpreadsheet()
.getSheetByName("Data")
.getDataRange()
.getValues();
var today = toUtcMidnight(new Date());
var todaysColumn = values[4].map(toUtcMidnight).map(Number).indexOf(+today);
var output = values[values.length - 1][todaysColumn];
return values[values.length - 1][todaysColumn];
}
You can use the method .pop() that returns and removes the last element from an array.
Make a copy of the original array first and use .pop() method and assign it to a new value.
var myArray = myArrayCopy
var lastArrayObject = myArrayCopy.pop()

Issues with indexOf in Javascript

I am having issues with indexOf in Javascript. It seems IndexOf fails to find a string when the it is obtained using .getValues() from a spreadsheet.
For example, the function below works fine.
function Narek() {
var array = ["Armine", "Narek", "Suren"]
var ggg = array.indexOf("Armine");
}
But this function, which gets the same names from the googlesheets returns -1.
function Narek() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("HL rota");
var array = ss.getRange(45,1,3,1).getValues();
var pickedHLM = ss.getRange(49,1,1,1).getValue();
var ggg = array.indexOf(pickedHLM);
Logger.log(pickedHLM)
Logger.log(ggg);
}
Any one can help?
While Range#getValue() returns the top-left cell content (in this case the value inside A49), #getValues() returns a two-dimensional array of the cell contents of the whole range (ie A45:A47). Each inner array holds the row's values.
So perhaps more similar to:
var values = [["Armine"], ["Narek"], ["Suren"]];
This can be transformed into your expectation of a flat array.
var array = values.map(function(row) { return row[0]; });
// ["Armine", "Narek", "Suren"]

How to remove quote mark from array

I have a script that will import data from a csv file in to a Google sheet. I would like to include the following to remove the quote marks from the data - .replace(/"/g, "") - but am not sure of the best place/syntax to add in to the existing script.
Do I add it in to the section where I convert the csv data to an array -
function CSVToArray_(strData){
var rows = strData.split("\n");
//Logger.log(rows.length);
var array = [];
for(n=0;n<rows.length;++n){
if(rows[n].split(',').length>1){
array.push(rows[n].split(','));
}
}
Logger.log(array);
return array;
}
...or to the section where the sheet gets updated with the array data ?
var impSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("CtrlSht").getRange("B8:B8").getValue();
var csvData = CSVToArray_(csvFile);// convert to 2D array
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(impSheet);
sheet.clear();
sheet.getRange(1,1, csvData.length, csvData[0].length).setValues(csvData);// write to sheet in one single step
Any guidance/suggestions would be greatly appreciated.
The code above is dangerous and will break if there is a comma within an element even if it is in quotes which is valid csv. I suggest checking out this library https://code.google.com/p/jquery-csv/. Also, are you wanting to remove quotes or are you wanting to convert string values to numbers? That is, are you getting "2" and wanting it to be just 2, if so, you may just be wanting to parse it into a number as follows: parseInt("2").
If you don't care about the above then the following should work:
function CSVToArray_(strData){
var rows = strData.split("\n");
//Logger.log(rows.length);
var array = [];
var array_inner;
// iterate over rows
for (n=0; n<rows.length; ++n) {
array_inner = rows[n].split(',');
if (array_inner.length>1) {
// iterate over columns
for (m=0; m<array_inner.length; m++) {
array_inner[m] = array_inner[m].replace(/"/g, "");
}
array.push(array_inner);
}
}
Logger.log(array);
return array
}

Categories

Resources