I'm querying from firebase realtime database, storing each result in an array, and returning this array. While the data is correct, I am not returning it in a type I want it to be in.
The code for this function is
exports.getprojects = functions.https.onRequest((req, res) => {
const uid = req.body.uid;
var projectref = fref.child('projects');
var projarr = [];
// Make the promise object for query
const projpromise = projectref.orderByChild('key').equalTo(uid).once('value');
// Another Promise for pushing to array
const pushpromise = projpromise.then(snap => {
var proj_item = snap.val();
// push to array
projarr.push(proj_item);
return proj_item;
}).catch(reason => {
console.log(reason)
return res.json(400);
})
// Respond with array
return pushpromise.then((proj_item) => {
return res.json(200, projarr);
}).catch(reason => {
console.log(reason)
return res.json(400);
})
});
This function queries all the right data, but returns in format like this :
[
{
"project_id": {
"project_title": "Test Project1",
"project_type": "Long Term"
},
...
]
What I need is for this function to return in format like below :
{
{
"project_id": {
"project_title": "Test Project1",
"project_type": "Long Term"
},
...
}
How can I achieve this? Any help is appreciated. Thank you!
To turn your array into a JSON object with just the key-value pairs, do something like this:
var array = [
{"project_id": {
"project_title": "Test Project1",
"project_type": "Long Term"
}},
{"project_id2": {
"project_title": "Test Project2",
"project_type": "Medium Term"
}},
{"project_id3": {
"project_title": "Test Project3",
"project_type": "Short Term"
}}
];
var result = {};
array.forEach(function(object) {
var key = Object.keys(object)[0];
result[key] = object[key];
})
console.log(result);