This Objectify code turns arrays of arrays into arrays of javascript objects.
I generally use it, especially if there are lots of columns, and the Google Form might change, because fixing up names is easier than fixing up indexes of columns (in your code.)
It can do all your data, one row of data, or get some data but instead of creating an array of objects, it creates an object of objects? This means you can lookup the one object you want by a key rather than iterating through a list and checking them (this function is objectifyWithKey).
/*
I often don't like working with lists of data. Sometimes I want to work with Javascript objects.
It means people can, in theory add or rename columns and you can at least recover.
*/
/*
objectify(Array headers, ArrayList rows): Used to turn rows of data into a list of named objects, like this:
[{hair=None, name=Bert, age=81.0},
{hair=Blond, name=Sally, age=34.0},
{hair=Black, name=Alf , age=68.0},
{hair=None, name=Stan, age=69.0},
{hair=Grey, name=Hilda, age=66.0},
{hair=Ginger, name=Fred, age=44.0}]
so you can:
var objectList = objectify(headers, rows)
Logger.log( objectList[1].hair) //get 2nd row's hair
* @param <Array> column headers as list
* @param <Array> rows as list
* @return [{}, {}...] a list of objects
*/
function objectify(headers, rows){
var newarray=[]
var obj
for(var y = 0; y < rows.length; y++){
obj = {};
for(var i = 0; i < headers.length; i++){
obj[headers[i]] = rows[y][i];
}
newarray.push(obj)
}
return newarray
}
/*
* @param <Sheet> the sheet you want to use
* @param <Integer> row number
* @param <Integer> header row number, usually 1
* @return {} a single object/row
*/
function objectifyOne( sheet, rowNum, headerRowNum){
var hNum = headerRowNum | 1 //Uses 1 if none passed in.
var headers = sheet.getRange( hNum, 1, 1, sheet.getLastColumn()).getValues()[0]
var data = sheet.getRange( rowNum,1, 1, sheet.getLastColumn()).getValues()
var object = objectify(headers, data)[0]
return object
}
function test_objectifyOne(){
logSheet.getRange("A4").setValue( objectifyOne( sheet, 52))
}
/*//////////////
objectifyWithKey(Array headers, ArrayList rows, String key): returns:
{Sally={hair=Blond, name=Sally, age=34.0},
Stan={hair=None, name=Stan, age=69.0},
Bert={hair=None, name=Bert, age=81.0},
Alf ={hair=Black, name=Alf , age=68.0},
Fred={hair=Ginger, name=Fred, age=44.0},
Hilda={hair=Grey, name=Hilda, age=66.0}}
so you can:
var objectDict = objectifyWithKey(headers, rows, "name") //key has to be unique, otherwise will overwrite
Logger.log(objectDict['Fred'].hair) //Note I can get a row by its keyed item.
>> "Ginger"
}
*
* @param <Array> headers
* @param <Array> rows
* @param <String> key name
* @return [{},{}] A list of objects.
*/
function objectifyWithKey(headers, rows, key){
var newarray=[]
var keyedObj = {}
for(var y = 0; y < rows.length; y++){
obj = {rowNum: y+2};
for(var i = 0; i < headers.length; i++){
obj[headers[i]] = rows[y][i];
}
keyedObj[obj[key]] = obj //leave the key in
}
return keyedObj
}