How could this Firestore function be improved, please? This is a question to help us learn to write better code. So by improved, I don't mean made shorter... I mean made clearer as to what it is doing, more efficient in terms of its operations, easier to understand and maintain. I found getting this code working very frustrating, so am including it here to help others learn from it, hopefully.
The code takes an object returned from Firestore which looks like this:
{
"GKXKsY34TAghSrNcaV6V": {
"finishedScoring": "true",
"id": "GKXKsY34TAghSrNcaV6V",
"role": "mentor",
"speaker": "Bob",
"yourScore": "60",
"title": "Aquaplex First Round Pitch"
},
etc.
}
This is passed into this code. The outcome desired is an array of arrays to allow us to use it as data in datatables.js. Yes, I'd have liked to use the Object source for datatables, instead of doing this array or arrays transform, but couldn't work out how to make it work in Firebase hosting with Node.js!
async function getDoc(db) {
let workArr = [];
let workArrArr = [];
try {
let doc = await db
.collection("user")
.doc("tNySnDyRdTfKCJnnpk9kHpVKTl12")
.collection("userwork")
.doc("000_user_work_index")
.get();
let workDoc = doc.data();
console.log("workDoc", workDoc);
//Create array of objects from Firestore object of objects
for (const [key, value] of Object.entries(workDoc)) {
workArr.push(value);
}
//Create array of arrays from array of objects
workArrArr = workArr.map(function (obj) {
return Object.keys(obj)
.sort()
.map(function (key) {
return obj[key];
});
});
return workArrArr;
} catch (err) {
console.log("Error getting document: ", err);
}
}
$(document).ready(function () {
getDoc(db).then((result) => {
console.log("RESULT OF getDoc: ", result);
$("#datatable-assessment").DataTable({
data: result,
columns: [
{ title: "Finished Scoring" },
{ title: "Doc ID" },
{ title: "Role" },
{ title: "Speaker." },
{ title: "Your Score" }
]
});
});
});
It does work... I just have a feeling it is not exactly efficient - so any advice please on how to improve it would be welcome.