[英]How to render an complex Object with nested Objects and arrays inside in React/JSX
我得到這個 Object 作為 API 的響應:
{
"transcript": {
"monologues": [
{
"speaker": 0,
"elements": [
{
"type": "text",
"value": "Bobby",
"ts": 2.99,
"end_ts": 3.55,
"confidence": 0.82
},
{ "type": "punct", "value": " " },
{
"type": "text",
"value": "tell",
"ts": 6.99,
"end_ts": 7.47,
"confidence": 0.74
},
{ "type": "punct", "value": " " },
{
"type": "text",
"value": "them",
"ts": 7.47,
"end_ts": 7.63,
"confidence": 0.44
},
{ "type": "punct", "value": "." }
]
}
]
}
}
如何從"elements"
數組中獲取"speaker"
和"value"
?
我嘗試通過“獨白”數組來 map,然后像這樣嵌套“元素”數組的另一個 map:
{transcription.transcript?.monologues.map((monologue, i) => {
return monologue.elements.map((text, i) => {
return <p>{text.value}</p>;
});
})}
但由於某種原因它不起作用。 我究竟做錯了什么?
您正在將map()
嵌套在map()
中。 這將導致在數組中具有數組的結構。
使用您的示例,您的最終結果將類似於:
[["bobby", " ", "tell", " ", "."], [/* Other monologues here if there were any*/]]
您可能想要的是值的平面數組,因此flatMap function 是您最好的朋友。
這應該更好:
{transcription.transcript?.monologues.flatMap((monologue, i) => {
return monologue.elements.map((text, i) => {
return <p>{text.value}</p>;
});
})}
免責聲明:我沒有測試過這段代碼,所以如果它不能按原樣工作,可能需要稍微調整一下。
我只是注意到在我的代碼中某處我正在對 json 響應進行字符串化,我不得不將其解析回來:
{JSON.parse(transcription).transcript?.monologues.map((monologue, i) => {
return monologue.elements.map((text, i) => {
return <p>{text.value}</p>;
});
})}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.