My current project involves learning AppScript through the use of Google Sheets as a practical example. I am attempting to generate a simple JSON object using data stored in the Sheet.
Table Example
[
{
"Name": "ABC",
"ID": "123",
"Price": 100,
"Qty": 1
},
{
"Name": "DEF",
"ID": "342",
"Price": 56,
"Qty": 2
},
{
"Name": "HIJ",
"ID": "233",
"Price": 90,
"Qty": 3
},
{
"Name": "IJK",
"ID": "213",
"Price": 68,
"Qty": 5
}
]
To achieve this, I initially followed a Youtube tutorial (https://www.youtube.com/watch?v=TQzPIVJf6-w) which focused on creating each column header as an object. However, my goal is to have the column name serve as the key and the row value as the value.
Here is the AppScript code I have been working on:
function doGet() {
var result={};
var rewards = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1')
.getDataRange()
.getValues();
result.rewardObj = makeObject(rewards);
//Logger.log(result.rewardObj);
return ContentService.createTextOutput(JSON.stringify(result))
.setMimeType(ContentService.MimeType.JSON)
}
function makeObject(multiArray)
{
var obj = {};
var colNames = multiArray.shift();
var rowNames = multiArray.slice(0,1);
var rowCount = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getLastRow();
var colCount = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getLastColumn();
for(var j=0;j<4;j++)
{
for(var i=0;i<4;i++)
{
//obj[colNames] = rowNames.map(function(item){return item[i];});
obj[colNames[j][i]] = multiArray[j][i];
}
}
Logger.log(rowCount)
Logger.log(colCount)
Logger.log(multiArray[57][12]);
return obj;
}
The current output is a single object:
{"rewardObj":{"Name":"ABC","ID":"123","Price":"100","Qty":"1"}}
Disclaimer: I do not have a background in programming and I am learning scripting in a somewhat unconventional manner. Please excuse any lack of basic knowledge on my part :)