Appscript: Add data from Google Spreadsheets to Firebase RealtimeDB node

拟墨画扇 提交于 2020-07-22 11:08:09

问题


Im trying to add data from google's sheets to firebase. This is my spreadsheet and this is what im trying to achieve -> RealtimeDb

This is what i have done so far, but it creates new node Items and put only the values without their names. Like

What it does --> Items >0

1: 'name of the product'

2: 'product barcode'..etc

------------------

What i want --> Items > examplebarcode :

itemname : 'radeonRX'

itembarcode: '234523523523'


var secret = '...'

function getFirebaseUrl(jsonPath) {
  return (
    'https://inventory.firebaseio.com/Items' +
    jsonPath +
    '.json?auth=' +
    secret
  )
}

function syncMasterSheet(excelData) {
 
  var options = {
    method: 'put',
    contentType: 'application/json',
    payload: JSON.stringify(excelData)
  }
  var fireBaseUrl = getFirebaseUrl('Items')

  UrlFetchApp.fetch(fireBaseUrl, options)
}

function startSync() {
  //Get the currently active sheet
  var sheet = SpreadsheetApp.getActiveSheet()
  //Get the number of rows and columns which contain some content
  var [rows, columns] = [sheet.getLastRow(), sheet.getLastColumn()]
  //Get the data contained in those rows and columns as a 2 dimensional array
  var data = sheet.getRange(1, 1, rows, columns).getValues()

  syncMasterSheet(data)
}

回答1:


Paraphrasing the question: The startSync function is passing an Array of Arrays but it should pass an Array of Objects.

You could use something like this:

/**
 * Converts an Array of Arrays into an Array of Objects
 *
 * @param {Array[]} values Array of Arrays. First "row" has column headers to be used as object keys
 * @return {Array}
 */
function objectise(values) 
  var keys = values[0]; // Column headers will be used as Object keys.
  var arr = values.map(function(row){
    var obj = {};
    keys.forEach(function(key,i){
       obj[key] = row[i];
    });
    return obj;
  });
}

Note: You might want to "normalize" the column headers to camel style or something similar

Related

  • Auto Sync google sheets to firebase without button


来源:https://stackoverflow.com/questions/62916873/appscript-add-data-from-google-spreadsheets-to-firebase-realtimedb-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!