0

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?

everspader
  • 1,272
  • 14
  • 44

1 Answers1

1

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());
}
Marios
  • 26,333
  • 8
  • 32
  • 52
  • Sins when there is the Object.values option in GAS? – RemcoE33 Sep 26 '20 at 13:22
  • I am not sure when it was introduced. But since Google scripts support ECMA6 you can do everything that JS does. @RemcoE33 – Marios Sep 26 '20 at 13:30
  • thanks. The autofill does not show it so I assumed that is could not be done... If I knew this 2 weeks ago :) btw.. have you noticed the strange formatting with array => formulas. – RemcoE33 Sep 26 '20 at 16:26