Google App Script changing order of firestore sheets

Asked

Viewed 19 times

0

I found a script to integrate Firestore with Google Sheets, but when running it, the columns are in order with each data update. How can I fix this?

https://i.imgur.com/Ski4t8q.png

A detail: I have more columns than those shown in the print (just to understand)

function getFirestore(){
  return FirestoreApp.getFirestore(email, key, projectId);
}

function importFromFirestore(){
  const firestore = getFirestore();

  const allDocuments = firestore.getDocuments('Visita').map(function(document){
    return document.obj;
  });

  const first = allDocuments[0];
  const columns = Object.keys(first);

  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.appendRow(columns);

  allDocuments.forEach(function(document){
    const row = columns.map(function(columns){
      return document[columns];
    });
    sheet.appendRow(row);
  });

1 answer

0


Looking at your code I believe that you should sort the column array, this can be done using something like Sort or reduce it, you can pass a proper algorithm for this.

This is because when you ask for a firestore information the "columns" will not come sorted, by the way because you are using the firestore you have no guarantee that all "columns" will exist there.


  //[..]
  const first = allDocuments[0];
  // Ordenar as colunas aqui
  const columns = Object.keys(first).reduce(/*Seu script de redução que retorna uma array ordenada*/);
  // ou
  const columns = Object.keys(first).sort(/*Seu script de ordenacao*/);

  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.appendRow(columns);
  //[..]

The idea presented uses reduce because it receives an initial value, a function that has as parameters an accumulator and the next element, so you can return an array ordered as you want, you can also pass a custom Sort function.

  • 1

    It helped a lot. It worked. Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.