Reputation: 11
I am working with the following function in Google Scripts
function writeToSheet(sheet, data, dataName, dataPts) {
var rows = [];
Logger.log(dataPts);
for (var z = 0; z < data.length; z++) {
var subRow = [];
for (var q = 0; q < dataPts.length; q++) {
subRow.push(dataName[z][dataPts[q]])
}
rows.push(subRow);
subRow = [];
}
Logger.log(rows);
dataRange = sheet.getRange(sheet.getLastRow()+1, 1, rows.length, rows[0].length);
dataRange.setValues(rows);
}
I pass the function a sheet to write to, the data which is an array of objects, the dataName which I'm using to try and extract data from the original array and dataPts which is an array of the property names that I'd like to extract from each object in the original array and nest as an array in the finished array - rows.
No matter how I try to make this work, I end up with an array build of the strings which if hardcoded into the function, would give me exactly what I want. However I can't work out how to do this dynamically so that it will work for any data I give it.
Does anyone have any ideas? I thought about trying to filter out properties from each object in the original array and then somehow turn the values from remaining keys into an array for each one, but I have no idea how to do this or if it is possible.
Appreciate any advice anyone might have :)
Upvotes: 0
Views: 64
Reputation: 9872
A simpler-to-read version of your solution, that uses the functional concept of mapping (applying some function to all elements of a container):
function writeToSheet(sheet, data, dataPts) {
// data is object[]
// dataPts is a string[] whose values are keys to each object in data
var rows = data.map(function (obj) {
var row = dataPts.map(function (key) {
var columnValue = obj[key];
return columnValue;
});
return row;
});
sheet.getRange(sheet.getLastRow()+1, 1, rows.length, rows[0].length)
.setValues(rows);
}
You can review the MDN website to learn more about the Array class method map
(and its functional pair reduce
).
(You could easily do away with the inner variables row
and columnValue
and just return
that value directly. I included them to help signify what that value is.)
Upvotes: 1
Reputation: 11
So I managed to get this working.
function writeToSheet(sheet, data, dataPts) {
var rows = [];
var data = data;
Logger.log(dataPts);
for (var z = 0; z < data.length; z++) {
var subRow = [];
for (var q = 0; q < dataPts.length; q++) {
subRow.push(data[z][dataPts[q]])
}
rows.push(subRow);
subRow = [];
}
Logger.log(rows);
dataRange = sheet.getRange(sheet.getLastRow()+1, 1, rows.length, rows[0].length);
dataRange.setValues(rows);
}
I realised the dataName variable was unnecessary and causing my function to treat this line as a string instead of pulling out the relevant value from the nested object:
subRow.push(data[z][dataPts[q]])
Upvotes: 1