Map an array of arrays with ReactJS
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.
Related videos on Youtube
Neil Kelsey
The queen honey bee has sex with on average 17-20 males in a single afternoon. Just like your mom.
Updated on June 04, 2022Comments
-
Neil Kelsey almost 2 years
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;
Great! All good so far, next up is my array of arrays - here's what this looks like in the console log
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!
-
Axnyff over 5 yearsWhat did you try? It should work if you map your inner array inside of your first component
-
Mozak over 5 yearsI guess value is coming as an array, so you might need to iterate the same.
-
-
Neil Kelsey over 5 yearsstef - So if I'm right in thinking, my first example is an array but my second example isn't actually an array of 4 arrays - it's as you said "Javascript object with a key-value mapping of country code to an array of data" ... this would explain why the first one worked and the second one didn't, so I need to treat the second version differently to my first simple array ... ok I think this is starting to make sense
-
Neil Kelsey over 5 yearsI got this working and seems like the best solution for me - anyone coming across my issue, it looks as if my issue was that my 'array of arrays' wasn't an array at all and was actually a javascript object which needed to be treated in a slightly different way as shown in the answer above - if any of my terminology isn't correct here feel free to correct me but that's the way I currently understand this