I keep coming to this thread looking for a neat way to log nested objects and arrays in GAS. I needed an output like this:
{
food : {
pizza : [
crust,
sauce,
topping,
cheese
]
},
drink : {
bananaShake : [
banana,
milk,
sugar
]
}
}
UPDATE: This is a more elegant solution: Logger.log(JSON.stringify(obj, null, 2))
. Thanks to @Zach's comment below.
In any case this is the function I was using earlier:
//-------------------------------------------------------------------------------
// Display the passed object in the Logger
// @param {object} obj - object to be logged
// @param {string} log - (for internal use only) final output sent to the logger
// @param {number} count - (for internal user only) keeps track of the number of
// iteration that the program is running in.
//-------------------------------------------------------------------------------
function logObj(obj, log, count) {
var def = {};
// Set default values to the passed arguments
obj = obj == undefined? def : obj;
log = log == undefined? '\n' : log;
count = count == undefined? 1 : count;
// If it's date object convert it to string
if(obj instanceof Date) {
obj = obj.toString();
}
// If it's a function represent it as a string
if(typeof obj == 'function') {
obj = 'function() {}';
}
// If it's an Object
if(typeof obj == 'object') {
var isArray = obj.constructor.name == 'Array';
var length = 0;
for(var i in obj) {
length++;
}
if(isArray) log += '[';
else log += '{';
if(length) {
log += '\n';
var num = 1;
for(var i in obj) {
// add tabs based on which iteration the program is running in
var tab1 = '';
var tab2 = ''; // this is one tab less than tab1
for(var k = 0; k < count; k++) {
tab1 += '\t';
if(k < (count - 1)) {
tab2 += '\t';
}
}
log += tab1;
if(!isArray) log += i + ' : ';
log += logObj(obj[i], '', count + 1);
if(num < length) {
log += ',\n';
}
num++;
}
log += '\n' + tab2;
}
if(isArray) log += ']';
else log += '}';
// if it's not the first iteration, return the log instead of printing it
if(count > 1) {
return log;
}
}
else if(count > 1) {
return obj;
}
else {
log = obj;
}
if(count == 1) {
Logger.log(log);
}
}