USer22999299
USer22999299

Reputation: 5674

how to iterate over dict and convert it to table record in react js using map?

having the following structure:

history: {
    https://jsonplaceholde.typicode.com/posts/41: "failed",
    https://jsonplaceholde.typicode.com/posts/42: "failed",
}

which is accessible via this.state.stats.history

how can I use map to iterate over the history and create table records generate table records?

something like this ->

<tr>
    {this.state.stats&& this.state.stats.history.map( ([key, value]) => {<th>key</th><th>value</th>})}
</tr>

Upvotes: 0

Views: 395

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074248

You'd use Object.entries to get an array of the entries in the object. You'll also need a fragment (or array) since map has to have a single value to return.

{this.state.stats
    ? Object.entries(this.state.stats.history).map(([key, value]) =>
          <><th>{key}</th><th>{value}</th></>
      )
    : false
}

(I pobably wouldn't do this directly in the structure being returned, I'd do it beforehand to avoid too much conditional logic in a JSX expression.

Upvotes: 2

Related Questions