Reputation: 41
I am trying to pull some information from a JSON array in a Google Sheet and take part of that info and copy it into two columns beside it.
The data I want is in Column L of my sheet (starting in row 2) and in the format:
[{"id": "XX:123456", "timestamp": "2020-01-27T19:25:51.303"}, {"id": "XX:654321", "timestamp": "2020-01-27T19:40:37.06"}]
Currently my script is as follows:
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("parsed");
var dataRange = sheet.getDataRange();
var lastRow = dataRange.getLastRow();
function parseData() {
for (var row=2; row<lastRow; row++)
{
var parseRange = sheet.getRange(row,12,5,1)
var json = JSON.parse(parseRange.getValue());
var lastObject = json.length-1;
var org = json[lastObject];
var orgID = org.id;
var timestamp = org.timestamp;
sheet.getRange(row, 13).setValue(orgID);
sheet.getRange(row, 14).setValue(timestamp);
}
}
This is very time consuming to process as it is reading and writing each row one by one. I had assumed the JSON array was already in sequential order, but having checked it appears to be random. What I ideally would like to do is sort the array by timestamp first, then take the object with the latest timestamp and write that data to column M and N, and to do this in a more efficient way.
Upvotes: 0
Views: 132
Reputation: 50846
let parseRange = sheet.getRange(1+1,12,lastRow-1,1);//col L
let values = parseRange.getValues();
let out = values.map(([row])=>{
let {id, timestamp} = JSON.parse(row).pop();
return [id, timestamp];
});
sheet.getRange(1+1, 13, lastRow-1, 2).setValues(out);
Upvotes: 1