从firestore格式化JSON数据



我正在使用一个云函数将我的数据库集合下载为JSON文件。

代码是

exports.csvJsonReport = functions.https.onRequest((request, response) => {
const db = admin.firestore()
const userAnswers = db.collection('/surveys/CNA/submissions')
return (
userAnswers
.get()
.then(querySnapshot => {
let answers = []
querySnapshot.forEach(doc => {
const answer = doc.data()
answers.push({ ...answer.answers, ...answer.anonUser })
})
response.setHeader('Content-disposition', 'attachment; filename=cna.json')
response.set('Content-Type', 'application/json')
response.status(200).send(answers)
})
.catch(error => {
console.log(error)
})
)
})

大多数时候我只关心value,但有时value嵌套在里面。。当它嵌套时,我将需要valuename

电流输出

[{
"2": {
"loopIndex": null,
"questionType": "multiChoice",
"value": "Farm owner",
"id": 1
},
"7": {
"1": {
"name": "Enviroment management",
"questionType": "responsiveMultiCheckBox",
"valueId": 4,
"value": "My top priority right now",
"id": 1
},
"2": {
"questionType": "responsiveMultiCheckBox",
"valueId": 3,
"value": "One of my top priorities",
"id": 2,
"name": "Financial management"
},
"3": {
"value": "My top priority right now",
"id": 3,
"name": "People management",
"questionType": "responsiveMultiCheckBox",
"valueId": 4
},
"4": {
"name": "Reproduction management",
"questionType": "responsiveMultiCheckBox",
"valueId": 4,
"value": "My top priority right now",
"id": 4
},
"5": {
"name": "Feed management",
"questionType": "responsiveMultiCheckBox",
"valueId": 4,
"value": "My top priority right now",
"id": 5
}
},
}]

期望输出:

[{
"2": {
"value": "Farm owner",
},
"7": {
"1": {
"name": "Enviroment management",
"value": "My top priority right now",
},
"2": {
"value": "One of my top priorities",
"name": "Financial management"
},
"3": {
"value": "My top priority right now",
"name": "People management",
},
"4": {
"name": "Reproduction management",
"value": "My top priority right now",
},
"5": {
"name": "Feed management",
"value": "My top priority right now",
}
},
}]

我试过

answer.answers.map(questionId => {
return console.log('value', questionId.value)
})

answers.answers.map不是函数

这是一把正在工作的小提琴:https://jsfiddle.net/uekbhta6/2/

let result = {}; 
// I am assuming that your answers array always contains one object with the rest of data    
for (let id in answers[0])
{
// If the value is present on the 1st level, push it to the buffer
if (answers[0][id].value) 
{
result[id] = answers[0][id].value;
}
// otherwise, iterate through the second level and push name/value to result buffer
else
{
result[id] = {};
for(let id2 in answers[0][id])
{
result[id][id2] = {
name:answers[0][id][id2].name,
value:answers[0][id][id2].value
};
}
}   
}
// wrap result in an array and print
console.log([result])

使用Array.reduce()可以做得更优雅,但时间已经晚了,我需要睡一会儿。

相关内容

  • 没有找到相关文章

最新更新