简体   繁体   English

如何在 React/JSX 中使用嵌套对象和 arrays 渲染复杂的 Object

[英]How to render an complex Object with nested Objects and arrays inside in React/JSX

I get this Object as a response from an API:我得到这个 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": "." }
        ]
      }
    ]
  }
}

How do i get "speaker" and "value" from the "elements" array?如何从"elements"数组中获取"speaker""value"

I tried to map through the "monologues" array and then nest another map of the "elements" array like this:我尝试通过“独白”数组来 map,然后像这样嵌套“元素”数组的另一个 map:

{transcription.transcript?.monologues.map((monologue, i) => {
  return monologue.elements.map((text, i) => {
    return <p>{text.value}</p>;
  });
})}

but for some reason it's not working.但由于某种原因它不起作用。 What am i doing wrong?我究竟做错了什么?

You are nesting a map() within a map() .您正在将map()嵌套在map()中。 This would result in a structure which has an array within an array.这将导致在数组中具有数组的结构。

Using your example, your end result would be something like:使用您的示例,您的最终结果将类似于:

[["bobby", " ", "tell", " ", "."], [/* Other monologues here if there were any*/]] 

What you probably want is a flat array of the values so the flatMap function is your best friend.您可能想要的是值的平面数组,因此flatMap function 是您最好的朋友。

This should be better:这应该更好:

{transcription.transcript?.monologues.flatMap((monologue, i) => {
  return monologue.elements.map((text, i) => {
    return <p>{text.value}</p>;
  });
})}

Disclaimer: I haven't tested this code so may have to tweak it a bit if it doesn't work as is.免责声明:我没有测试过这段代码,所以如果它不能按原样工作,可能需要稍微调整一下。

I just noticed that somewhere in my code i was stringifying the json response and i had to parse it back:我只是注意到在我的代码中某处我正在对 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM