Neil Kelsey
Neil Kelsey

Reputation: 841

Map an array of arrays with ReactJS

So what I'm trying to do is map an array of arrays

Firstly I've started simple and got this working - a simple array of countries (well, country codes)

{countries.map((value, index) => {
  return (
    <span
      key={index}
      className="semi-bold clear"
    >
      <h2>Hello world</h2>

      <hr />
    </span>
  )
})}

And here's what it looks like, browser on the left and console on the right;

Console log 1

Great! All good so far, next up is my array of arrays - here's what this looks like in the console log

Console log 2

So this is an array of 4 arrays and this is where I fall down, using the same piece of example code above but replacing the first array with this array of 4 arrays but when I do so the whole thing falls over, I don't understand why that wouldn't work, I was expecting to return 4 hello worlds like before

In case it's not clear, here's a mock up of what I eventually want to achieve in the browser!

Finished browser view

Upvotes: 2

Views: 22443

Answers (1)

stef
stef

Reputation: 14268

You have a Javascript object with a key-value mapping of country code to an array of data.

To loop over a Javascript object you need to do something like this:

render () {
  const historicalData = this.groupedByCountryHistoricalFilings()

  return(
    <div>
      {Object.keys(historicalData).map((key) => {
         return (
           <div key={key}>
              <h1>{key}</h1>
              {historicalData[key].map((dataItem) => {
                return (
                 <span key={dataItem.id}>{dataItem.title}</span>
                )
               })}
           </div>
         )
       })}
     </div>
   )
 }

This assumes that each item in each array has an id and a title. Change these as appropriate.

Clearly that's quite complex to read, so I'd recommend breaking this up into smaller components - a CountryHistoricalList component which could take a country code, title and an array of data perhaps.

Upvotes: 6

Related Questions