When working with Google Apps Script, I have a specific task that involves looping through data and writing only certain keys to a sheet. I want this looping operation to be done in a separate function rather than directly in the main function, as it will be used multiple times.
How can I modify the print_data()
function to achieve the same output as it does within the main()
function?
function main() {
const data = [{"key_1":10,"key_2":20,"key_3":30},{"key_1":40,"key_2":50,"key_3":60}];
// Print data
for (let i=0; i<data.length; i++) {
const d = data[i];
Logger.log([[d.key_1,d.key_3]]);
}
const keys = [[d.key_1, d.key_2]];
print_data(data, keys);
}
function print_data(data, keys) {
for (let i=0; i<data.length; i++) {
const d = data[i];
Logger.log(keys);
}
}
Solution:
function test_main() {
const data = [{"key_1":10,"key_2":20,"key_3":30},{"key_1":40,"key_2":50,"key_3":60}];
const keys = ["key_1","key_3"];
// print_data(data, keys);
print(data, keys);
}
function print(data, keys) {
ss = SpreadsheetApp.getActiveSpreadsheet();
sheet = ss.getSheetByName("Test");
sheet.clear();
for (let i=0; i<data.length; i++) {
arr = Array(keys.map(k => data[i][k]));
sheet.getRange(i+1,1,1,2).setValues(arr);
}
}