Can you help me create a Google Apps Script that will return values from a database to an on-sheet form? - arrays

My issue is returning the values saved in a database to the form in each cell in the range. The saveToDB script below is able to save the values from the form to the database, but I don't know how to retrieve those values. Hope you could help me. Thanks so much!
Form: sample form
Database: database sample
function saveToDB(){
range = ["C2","C4","C6"]
var newRange = range.map(f => formSheet.getRange(f).getValue())
dbSheet.appendRow(newRange)
}
function loadToForm(){
range = ["C2","C4","C6"]
var dbArray = dbSheet.getRange(2,1,dbSheet.getLastRow(),dbSheet.getLastColumn()).getValues()
var newArray = dbArray.filter(function(row){
if(row[0] === "Fred" && row[0] !== -1){
return row !== ""
}
})
//Don't know how to return each value to each cell in the range
//Update - this is the code that did it
range.map((f,i) => formSheet.getRange(f).setValue(newArray[0][i]))
}

function saveToDB() {
const ss = SpreadsheetApp.getActive();
const fsh = ss.getSheetByName('Form Sheet Name');
const dsh = ss.getSheetByName('Database Sheet Name')
let arr = ["C2", "C4", "C6"].map(e => fsh.getRange(e).getValue());
dsh.appendRow(arr);
}
function loadToForm() {
const range = ["C2", "C4", "C6"];
const ss = SpreadsheetApp.getActive();
const dsh = ss.getSheetByName('Database Sheet Name');
const fsh = ss.getSheetByName('Form Sheet Name');
let r = SpreadsheetApp.getUi().prompt('Row Number','Enter Row Number', SpreadsheetApp.getUi().ButtonSet.OK_CANCEL);
if(r.getSelectedButton() == SpreadsheetApp.getUi().Button.OK) {
let vs = dsh.getRange(row, 1, 1, dsh.getLastColumn()).getValues()[0];
range.forEach((e,i) => { fsh.getRange(e).setValue(vs[i])
});
}
}

All you have to do is use the setValue() function and iterate through each cell like so:
function loadToForm(){
range = ["C2","C4","C6"]
var dbArray = dbSheet.getRange(2,1,dbSheet.getLastRow(),dbSheet.getLastColumn()).getValues()
var newArray = dbArray.filter(function(row){
if(row[0] === "Fred" && row[0] !== -1){
return row !== ""
}
})
//Remove useless extra dimension from array
newArray = newArray[0];
//Solution 1 using RangeList
var ranges = formSheet.getRangeList(range).getRanges();
for(var i in newArray){
ranges[i].setValue(newArray[i]);
}
//Solution 2 not using RangeList
for(var i in newArray){
formSheet.getRange(range[i]).setValue(newArray[i]);
}
}

Related

Adding Google Classroom ID based on user enrollment code

I have a spreadsheet where a user can list classes and Google Classroom enrollment codes, represented by the array userClassCodes. This array is allowed to contain blank values when the range contains blank cells. This array is represented in the following way:
[ ['class name 01', 'class code 01'], ['class name 02', 'class code 02'], ...]
I am using the Google Classroom API to get a list of the sheet user's enrollment codes and course IDs. I would like to iterate through the userClassCodes array and add the class ID to the array when there is a matching class code in the API response. If there is no match, I would like to preserve the entry in the array and add a blank value for the course ID.
I am having trouble properly constructing an array that will achieve the desired output. Here is my current code:
function googleClassroomImport() {
var userClassCodes = SpreadsheetApp.getActive().getRange("Sheet1!A1:B25").getValues();
var newArray = [];
var options = {
teacherId: 'me',
courseStates: 'ACTIVE',
pageSize: 50
};
var response = Classroom.Courses.list(options);
response.courses.forEach(function (course) {
for (let i = 0; i < userClassCodes.length; i++) {
if (userClassCodes[i][1] == course.enrollmentCode) {
newArray.push([userClassCodes[i][0], userClassCodes[i][1], course.id]);
}
else {
newArray.push([userClassCodes[i][0], userClassCodes[i][1], ""]);
}
}
});
console.log(newArray);
}
Try this:
function googleClassroomImport() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0");
const rg = sh.getRange("A1:B25");
const vs = rg.getValues().filter(r => r[0] && r[1]).filter(e => e);
const arr = vs.map(r => r[1]);
var options = { teacherId: 'me', courseStates: 'ACTIVE', pageSize: 50 };
var response = Classroom.Courses.list(options);
response.courses.forEach(course => {
let idx = arr.indexOf(course.enrollmentCode);
if (~idx) {
vs[idx].push(course.id);
} else {
vs[idx].push('');
}
});
console.log(newArray);
}

How to trim space from a property of an object present in an array of object?

I have an array of objects with me:
Array of objects
Now, I want to change the property name of an particular object(not the value). For ex:
My object has attribute PRODUCT NAME:'BAJAJ Brahmi Amla Hair Oil 300 ml' in my data.
Required result:
PRODUCT_NAME:'BAJAJ Brahmi Amla Hair Oil 300 ml'
So, how can I replace the space in my property to an '_'.
Language used: React.js
I tried this function but it's not working for my desired result:
const productList = () => {
for (let i = 0; i < data.length; i++) {
let obj = data[i];
console.log(obj);
Object.keys(obj).forEach((key) => {
var replacedKey = key.trim().toUpperCase().replace(/\s\s+/g, "_");
if (key !== replacedKey) {
obj[replacedKey] = obj[key];
delete obj[key];
}
});
}
};
Can somebody explain why is this not working ?
can you please change replace(/\s\s+/g, "_") to replace(" ", "_") and then try, as you can see the below code
const productList = () => {
for (let i = 0; i < data.length; i++) {
let obj = data[i];
console.log(obj);
Object.keys(obj).forEach((key) => {
var replacedKey = key.trim().toUpperCase().replace(" ", "_");
if (key !== replacedKey) {
obj[replacedKey] = obj[key];
delete obj[key];
}
});
}
};
const string = "PRODUCT NAME"
console.log(string.trim().toUpperCase().replace(" ", "_"))

Combining a loop function and IF condition in google app scirpt

New to google app script and trying to create a function which combines loop (can be map, for or forEach) and IF condition.
See public spreadsheet for data: https://docs.google.com/spreadsheets/d/1V7CpCxBH0lg6wi1TAhfZJP5gXE8hj7ivQ8_ULxLSLgs/edit?usp=sharing
I wish to create an array inside a variable. In this array I want all quantity of column "D" but only if column "C" is "Buy".
This is the code I have tried but it comes back empty:
const ss = SpreadsheetApp.getActiveSpreadsheet();
const historySheet = ss.getSheetByName('Blad1');
function quantBuy () {
const searchRange = historySheet.getRange(3,2,historySheet.getLastRow()-1, 2)
let rangeValues = searchRange.getValues();
for (i = 0; i < historySheet.getLastRow()-1; i++) {
if (rangeValues[i] === 'Buy') {
console.log(i);
}}}
Any help is appreciated.
getValues is 2 demiensional
function quantBuy () {
const searchRange = historySheet.getRange(3,3,historySheet.getLastRow()-1, 2)
let rangeValues = searchRange.getValues();
for (let i = 0; i < rangeValues.length; i++) {
if (rangeValues[i][0] === 'Buy') {
console.log(rangeValues[i][1]);
}
}
}

loop through array, find sub-string in cell, replace text in Google Sheets

I want to create a function in Google Sheets that loops through an array, finds a string, and replaces the text of the string with a new value. I have code that works but it only replaces the text if the cell ONLY contains the string (ie search for "office" replace with "Office" only works if the cell only contains "office). I want to be able to replace "office" with "Office" even if the cell contains "office 867". Below is the code that works. Also, how can I get the function to search column A, row 1 to whatever? As of now, the function only finds and replaces if the values are in B2 to whatever (ie the first column A is not searched and the first row of every other row is not searched. Function works on B2 to whatever but won't work on B1, C1, D1, etc. I know it is because of the searchRange variable but I can't figure out how to set the parameters so that it searches the entire sheet (ie all columns and all rows). So here's the code I have so far. The questions I have are in the code as comments:
// This code works but ONLY if entire cell matches the string being searched for
// I want to search for all cells that contain the string even if other text is present
// So if cell contains "office 98" I want to change that to "Office 98"
// If cell contains "blg 78" I want to change that to "Building 78"
// If cell contains "space 9876" I want to change that to "Space 9876"
// Also, how do I change the var searchRange so that the range is the entire sheet?
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var rangeData = sheet.getDataRange();
var lastColumn = rangeData.getLastColumn();
var lastRow = rangeData.getLastRow();
var searchRange = sheet.getRange(2,2, lastRow-1, lastColumn-1);
function findReplace() {
var rangeValues = searchRange.getValues();
for ( i = 0; i < lastColumn - 1; i++){
for ( j = 0 ; j < lastRow - 1; j++){
if(rangeValues[j][i] === "office"){
sheet.getRange(j+2,i+2).setValue("Office");
}else if (rangeValues[j][i] === "blg"){
sheet.getRange(j+2,i+2).setValue("Building");
}else if (rangeValues[j][i] === "space"){
sheet.getRange(j+2,i+2).setValue("Space");
};
};
};
};
You can use getDataRange function [1] to get the entire range where there's data in the sheet. To avoid matching the entire string, use indexOf method [2] to check if the searched string is inside the cell string. To only replace the searched string, use replace function [3] on the cell value. I also put a string validation so any other type of cell value will be ignored (Number, Date, Boolean):
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var searchRange = sheet.getDataRange();
var lastColumn = searchRange.getLastColumn();
var lastRow = searchRange.getLastRow();
function findReplace() {
var rangeValues = searchRange.getValues();
for ( i = 0; i < lastColumn; i++){
for ( j = 0 ; j < lastRow; j++){
var value = rangeValues[j][i];
if(typeof value != "string") { continue; }
if(value.indexOf("office") > -1){
var newValue = value.replace("office", "Office")
sheet.getRange(j+1,i+1).setValue(newValue);
}
else if (value.indexOf("blg") > -1){
var newValue = value.replace("blg", "Building")
sheet.getRange(j+1,i+1).setValue(newValue);
}
else if (value.indexOf("space") > -1){
var newValue = value.replace("space", "Space")
sheet.getRange(j+1,i+1).setValue(newValue);
};
};
};
};
[1] https://developers.google.com/apps-script/reference/spreadsheet/sheet#getdatarange
[2] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
[3] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
function findReplace() {
const ui=SpreadsheetApp.getUi();
const ss=SpreadsheetApp.getActive();
const srchA=['office','blg','space'];
const vA=['Office','Building','Space'];
const sh=ss.getActiveSheet();
const rg=sh.getRange(2,2,sh.getLastRow()-1,sh.getLastColumn()-1);
const v=rg.getValues();
v.forEach(function(r,i){
r.forEach(function(c,j){
srchA.forEach(function(s,k){
if(v[i][j].toString().includes(s)) {
sh.getRange(i+2,j+2).setValue(vA[k]);
}
});
});
});
}
or maybe this:
function findReplace() {
const ui=SpreadsheetApp.getUi();
const ss=SpreadsheetApp.getActive();
const srchA=['office','blg','space'];
const vA=['Office','Building','Space'];
const sh=ss.getActiveSheet();
const rg=sh.getRange(2,2,sh.getLastRow()-1,sh.getLastColumn()-1);
srchA.forEach((s,k) => {
rg.createTextFinder(s).matchEntireCell(false).findAll().forEach(rg => {
rg.setValue(vA[k]);
});
}
}

combine two array as key value pair

I have two array as follows
var field_array=["booktitle","bookid","bookauthor"];
var data_array=["testtitle","testid","testauthor"];
I want to combine these two array and covert it to the following format
var data={
"booktitle":"testtitle",
"bookid":"testid",
"bookauthor":"testauthor"
}
I want to insert this data to database using nodejs
var lastquery= connection.query('INSERT INTO book_tbl SET ?',data, function (error, results, fields) {
if (error) {
res.redirect('/list');
}else{
res.redirect('/list');
}
});
Please help me to solve this.
var field_array = ["booktitle", "bookid", "bookauthor"];
var data_array = ["testtitle", "testid", "testauthor"];
var finalObj = {};
field_array.forEach(function (eachItem, i) {
finalObj[eachItem] = data_array[i];
});
console.log(finalObj); //finalObj contains ur data
You also can use reduce() in a similar way:
var field_array=["booktitle","bookid","bookauthor"];
var data_array=["testtitle","testid","testauthor"];
var result = field_array.reduce((acc, item, i) => {
acc[item] = data_array[i];
return acc;
}, {});
console.log(result);
Here I explaned my code line by line..Hope it will help
var field_array = ["booktitle", "bookid", "bookauthor"];
var data_array = ["testtitle", "testid", "testauthor"];
//Convert above two array into JSON Obj
var jsondata = {};
field_array.forEach(function (eachItem, i) {
jsondata[eachItem] = data_array[i];
});
//End
//Store Jsondata into an array according to Database column structure
var values = [];
for (var i = 0; i < jsondata.length; i++)
values.push([jsondata[i].booktitle, jsondata[i].bookid, jsondata[i].bookauthor]);
//END
//Bulk insert using nested array [ [a,b],[c,d] ] will be flattened to (a,b),(c,d)
connection.query('INSERT INTO book_tbl (booktitle, bookid, bookauthor) VALUES ?', [values], function(err, result) {
if (err) {
res.send('Error');
}
else {
res.send('Success');
}
//END

Resources