如何获取一组嵌套的JSON对象并将其数据附加到可编辑的文本字段



我有一组嵌套的JSON对象,需要将其附加到文本字段中。有6个对象,我不想硬编码6个文本字段。我以前使用过.map功能,但在这种情况下无法使用它。

const [questions, setQuestions] = useState('');
const fetchQuestions = async () => {
setQuestions( await fetch(`/fiscalyears/FY2023/intakes/${params.id}/details/questions`)
.then((response) => response.json())
);
};
useEffect(() => {
fetchQuestions();
}, []);

在我的退货声明中:

{questions?.map((row) => (
<TextField
className="text-field"
value={row?.Value || ''}
variant="outlined"
margin="normal"
label={row['FieldName']}
/>
))}

以下是我的JSON:的缩短版本

{
"Consulting": [
{
"Question": null,
"Response": null
}
],
"FED": [
{
"Question": "1. Is there any impact to the region applications?",
"Response": "No"
},
{
"Question": "2. If number 1 is "Yes", then are any of the below applications being 
impacted?",
"Response": "No"
},
{
"Question": "3. Are you changing data structure? rn",
"Response": null
}
],
"IPE": [
{
"Question": "1. Do you need compute (servers), storage, databases, and/or platform capacity for your effort?",
"Response": "Yes"
},
{
"Question": "2. If yes, please describe:",
"Response": "I need servers"
},
{
"Question": "3. Do you need Database Services?rn",
"Response": null
}
]
}

您只能对数组使用map方法。对于遍历对象,可以使用

Object.keys(questions).map(function(key, index) {
//do something here
})

否则你可以使用for循环,但我不喜欢

for (var key in questions) {
if (questions.hasOwnProperty(key)) {
// use questions[key]
}
}

最新更新