我正在查询firebase实时数据库,将每个结果存储在一个数组中,然后返回此数组。虽然数据是正确的,但我没有按照我希望它的类型返回它。
此功能的代码是
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);
})
});
此函数查询所有正确的数据,但返回的格式如下:
[
{
"project_id": {
"project_title": "Test Project1",
"project_type": "Long Term"
},
...
]
我需要的是这个函数以下面的格式返回:
{
{
"project_id": {
"project_title": "Test Project1",
"project_type": "Long Term"
},
...
}
我怎样才能做到这一点?任何帮助表示赞赏。谢谢!
答案 0 :(得分:1)
要将数组转换为仅包含键值对的JSON对象,请执行以下操作:
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);