Home > OS >  How to render an complex Object with nested Objects and arrays inside in React/JSX
How to render an complex Object with nested Objects and arrays inside in React/JSX

Time:09-13

I get this Object as a response from an 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?

I tried to map through the "monologues" array and then nest another map of the "elements" array like this:

{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?

CodePudding user response:

You are nesting a map() within a 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.

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.

CodePudding user response:

I just noticed that somewhere in my code i was stringifying the json response and i had to parse it back:

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