Reputation:
I have a code that finds the value in A column and returns other column values in that row:
function getCurrentRow(e) {
var parsedJson = JSON.parse(e.postData.contents);
var ss = SpreadsheetApp.openById("...");
var sheet = ss.getSheetByName("List");
var column = sheet.getRange("A:A");
var values = column.getValues();
var row = 0;
while ( values[row] && values[row][0] !== parsedJson.myValue ) {
row++;
}
if (values[row][0] === parsedJson.myValue) {
var record = {};
record['top'] = sheet.getRange((row+1), 2).getValue();
record['bottom'] = sheet.getRange((row+1), 3).getValue();
return ContentService.createTextOutput(JSON.stringify(record)).setMimeType(ContentService.MimeType.JSON);
}
}
It works, but when it can't find myValue it returns
TypeError: Cannot read property "0" from undefined.
in this line:
if (values[row][0] === parsedJson.myValue) {
How can I fix that and return "Can't find myValue" instead?
Upvotes: 1
Views: 171
Reputation: 50584
While values[row]
exists, you're adding 1 to row
with row++
. Say, There are 5 rows(Index:0 to 4) in A:A
and values[row][0] !== parsedJson.myValue
in all 5 rows. At the final row(Actual row 5; Index:4), row++
adds 1 and the row
is now 5 (Index:5). But values[5]
doesn't exist and is undefined, which has no [0]
property.
Add a another condition inside while
condition:
var lastRowIndex = values.length;
while ( values[row] &&
values[row][0] !== parsedJson.myValue
&& row < lastRowIndex ) {
row++;
}
Upvotes: 1
Reputation: 11278
if (values[row][0] === parsedJson.myValue) {
should be
if (values[row] && values[row][0] === parsedJson.myValue) {
Upvotes: 1