我如何获取一组嵌套的 JSON 对象并将它们的数据附加到可编辑的文本字段?
How can I take a group of nested JSON objects and append their data to an editable text field?
我有一组嵌套的 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();
}, []);
在我的 return 声明中:
{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? \r\n",
"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?\r\n",
"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]
}
}
我有一组嵌套的 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();
}, []);
在我的 return 声明中:
{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? \r\n",
"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?\r\n",
"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]
}
}