I wrote a simple iterator to loop trough a JSON object and parse the object into a new form. This works as expected in almost any JS environment. (For example in the console( However, the function below returns an empty array when executed in AppScript.
returns : [[], [], [], [], []]
This problem seems to be AppScript specific. Before I submit a bug through Google Developer Group I like to understand if this might be an App Script specific and intended behavior.
function parseBQData(/*tableData, request*/) {
var tableData = [["20220301","(none)","(direct)","3","1","1"],["20220301","organic","google","3","1","1"],["20220302","(none)","(direct)","4","2","2"],["20220302","organic","bing","1","1","1"],["20220303","(none)","(direct)","1","1","1"]]
try {
// store the array of dimensions and metrics in a variable called 'fields'
var fields = ["date", "medium", "source", "pageviews", "sessions", "users"]
// create a new empty array to store the parsed data
var newtableData = new Array();
// loop through each row in the tableData
for (var i = 0; i < tableData.length; i++) {
Logger.log(tableData[i]) // This returns: [20220301, (none), (direct), 3, 1, 1], [2022]
// create a new empty array to store the current row
var wrapper = new Array();
// loop through each column in the row
for (var j = 0; j < fields.length; j++) {
wrapper[fields[j]] = tableData[i][j]; /// <-is this not working?
Logger.log("Test Log:")
Logger.log("This is the updated field stored in the wrapper:"+wrapper[fields[j]]) // Returns : "20220301"
Logger.log("Lets check the wrapper if has the date/first value : " + wrapper.date ) // Returns "20220301"
// the wrapper does not dissapear but appears as empty when accessed as in root, the assignment abovew worked and the key value pair is accessible
Logger.log("Wrapper : " + JSON.stringify(wrapper)) // This returns always "Wrapper : []" Stringify is solely used to see that atleast something is returned and the wrapper is accesible
Logger.log("This is the current cell: "+fields[j]+" : "+tableData[i][j]) // This returns : "This is the current cell: date : 20220301" ... This is the current cell: medium : (none)
// So in conclusion All values and Arrays are accessible
// store the column data in the current row array, using the column header as the key
}
// add the current row to the new array of parsed data
newtableData.push(wrapper);
}
// return the new array of parsed data
Logger.log(newtableData) //This returns: "[[], [], [], [], []]""
return newtableData;
// if there is an error parsing the data, print the error to the log
} catch (e) {
Logger.log("Error parsing data")
Logger.log(e)
}
}
#Edit: Added some logging and comments
parseBQData? Which line is used to log the return:[[], [], [], [], []]?