user2041458
user2041458

Reputation: 97

Modify JavaScript Object and use setRowsData to write to individual cell

I am using getRowsData to retrieve the information, but I would like to modify the values stored within a JS object and then write that modified value back into the cell. I would like to use the normalized header variable that was created with getRowsData to write back into the cell. So if I retrive the info using

var thirdEmployee = employeeObjects[2];
var stringToDisplay = "The third column is: " + thirdEmployee.firstName + " " + thirdEmployee.lastName;
stringToDisplay += " (id #" + thirdEmployee.employeeId + ") working in the ";
stringToDisplay += thirdEmployee.department + " department and with phone number ";
stringToDisplay += thirdEmployee.phoneNumber;
ss.msgBox(stringToDisplay);

Then, for example, I would assign a new value to the Javascript object thirdEmployee.phoneNumber; and then have it written into the proper location in the range (i.e., active row, column # based on header).

thirdEmployee.phoneNumber = "123-555-5555";
thirdEmployee.phoneNumber.setNewValue();
  or
setNewValue.thirdEmployee.phoneNumber;

Basically, it would be a modified version of setRowsData but allow for modification of one object and then telling that object to be written into the spreadsheet based on the active row & column based on the header.

Anyone use or know how to do this?

Upvotes: 1

Views: 337

Answers (1)

Mogsdad
Mogsdad

Reputation: 45720

The setRowsData() helper function from the Writing Data from JavaScript Objects to a Spreadsheet tutorial already supports the ability to write a single object. To use it, though, you need to provide both of the optional parameters optHeadersRange and optFirstDataRowIndex.

If we assume that your headers are in row 1, here's how you could update thirdEmployee:

var headersRange = sheet.getRange(1, 1, 1, sheet.getLastColumn());
var thirdEmployee = employeeObjects[2];
...
thirdEmployee.phoneNumber = "123-555-5555";

setRowsData(sheet, [thirdEmployee], headersRange, 3 );

Upvotes: 1

Related Questions