问题
I'm trying to transfer Firebase RealtimeDB data into Google Sheets using AppScript.
I need a way to extract ID, Department, and Surname strings from the DB while it is received as such from the Logs below.
I use .childByAutoID() which has the following effect on the DB.
My database:
Desired result in spreadsheet:
function writeSheets() {
var firebaseUrl = "<my-database>.firebaseio.com/Attendees";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);
var data = base.getData();
console.log(JSON.stringify(data));
var ss = SpreadsheetApp.openById("<my-spreadsheet>");
var sheet = ss.getSheetByName("Sheet1");
var num = 2;
range = ss.getRange("A"+num+":C"+num+"");
for(var i in data) {
var values = [[data[i][0], data[i][1], data[i][2]]];
range.setValues(values);
num += 1;
range = sheet.getRange("A"+num+":C"+num+"");
}
}
base.getData() reads it as:
{
"-M4PTaIESKhQZhreHSE6":
{"Department":"HR",
"ID":"1009",
"Surname":"Blanc"},
"-M4PTgaNIE8BDqAcMr5y":
{"Department":"Accounting",
"ID":"1002",
"Surname":"Sandler"},
"-M4PTmOxxNge0Xfe_ez0":
{"Department":"Creative",
"ID":"1009",
"Surname":"Tolkien"}
}
I
Logs: [20-04-09 00:11:31:653 HKT] {"-M4PTaIESKhQZhreHSE6":{"Department":"HR","ID":"1009","Surname":"Blanc"},"-M4PTgaNIE8BDqAcMr5y":{"Department":"Accounting","ID":"1002","Surname":"Sandler"},"-M4PTmOxxNge0Xfe_ez0":{"Department":"Creative","ID":"1010","Surname":"Tolkien"}}
回答1:
Use Object.values and Array.map :
const data = {
"-M4PTaIESKhQZhreHSE6":
{"Department":"HR",
"ID":"1009",
"Surname":"Blanc"},
"-M4PTgaNIE8BDqAcMr5y":
{"Department":"Accounting",
"ID":"1002",
"Surname":"Sandler"},
"-M4PTmOxxNge0Xfe_ez0":
{"Department":"Creative",
"ID":"1009",
"Surname":"Tolkien"}
};
const out = Object.values(data).map(Object.values);
//or to change order: Object.values(data).map(({Department:dp,ID,Surname:sn})=>[ID,dp,sn]);
console.info(out);
来源:https://stackoverflow.com/questions/61105316/need-a-way-to-extract-specific-data-from-firebase-realtimedb-to-google-sheets