user9348468
user9348468

Reputation:

Iterate through Object of arrays in react js

I am trying to render the following json response.

 "tickets": {
        "tickets": [
            "A Nuisance in Kiribati",
            "A Nuisance in Saint Lucia"
        ]
  }

My attempt is as below.

const display4 = Object.keys(this.state.ticketsList).map(
  (keyName, keyIndex) => {
    return (
      <div className="my-posts">
        <li key={keyIndex}>{keyName}_{keyIndex}:</li>
        <li key={keyIndex}>{this.state.ticketsList[keyName]}</li>
      </div>
    );
  }
);

But it will display the tickets array in a single line without any separation even. I tried all most all the things on the internet. But nothing works yet. How can I fix this?

Upvotes: 1

Views: 96

Answers (1)

Dylan Kerler
Dylan Kerler

Reputation: 2187

You are reading the raw array and displaying it - that's why it displays all in one line. this.state.ticketsList[keyName] is the array. So you need to iterate through it in an additional loop to display each item.

Try this:

const display4 = Object.values(this.state.ticketsList).map(
  tickets => tickets.map((ticketName, index) =>
      <div className="my-posts">
        <li key={index}>{ticketName}_{index}:</li>
        <li key={index}>{ticketName}</li>
      </div>
  )
);

Upvotes: 1

Related Questions