everspader
everspader

Reputation: 1710

How to get a script to append the data in the right order in Google Sheets?

So I'm trying to insert some date from a form into a Google sheet. In my .HTML file, I am getting the data from the form and storing in an object like:

var data = {
  name: nameInput.value,
  company: "None",
  email: emailInput.value,
  date: dateInput.value
}; 

Then I have a function that actually appends the data:

function appendData(data) {
  var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
  var dataArray = [];
  for (var i in data){
    dataArray.push(data[i]);
  }
  ws.appendRow(dataArray);
}

I want to insert the data in the same order as it is collected in the object (Name, company, email, date) but when I use the appedData function I get the opposite (date, email, company, name). Same happens if I use Object.values(data). The only way it works properly is if I append it manually as ws.append([data.name, data.company, data.email, data.date]). Why is this happening?

Upvotes: 0

Views: 170

Answers (1)

Marios
Marios

Reputation: 27350

JSON objects have no specific order and are not guaranteed to keep the order you put things in. If you want keys in an order, you should put them in an array which will maintain order.

JSON objects do not preserve the order of the elements you put in. If you want the elements to be in order, you should put them in array instead.

var data = [
             {name: nameInput.value},
             {company: "None"},
             {email:emailInput.value},
             {date: dateInput.value}
           ]

Solution:

function appendData() {
  var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
  var dataArray = [];
  var data = [
             {name: nameInput.value},
             {company: "None"},
             {email:emailInput.value},
             {date: dateInput.value}
           ]
  
  for (var i in data){
    dataArray.push(Object.values(data[i]));
  }  
  ws.appendRow(dataArray.flat());
}

Upvotes: 1

Related Questions