let array = this.props.data.allGoogleSheetSpacesRow.edges;
const results = [...array.reduce((r, e) => {
let k = `${e.node.twitter}`;
if(!r.has(k)) r.set(k, {...e, count: 1})
else r.get(k).count++
return r;
}, new Map)]
I'm using reduce to get a count of duplicate twitter usernames in my array to create a leaderboard like so:
let leaderboard = results;
console.log(leaderboard);
return (
{leaderboard.map((item, index) => (
<div key={index}>
{item.value.map((c, i) => (
<div key={i}>
<h3>{c.count}</h3>
<h3>{c.node.twitter}</h3>
<hr />
</div>
))}
</div>
))}
)
I'm trying to map over the map to render the data but I'm not sure how to. I get Cannot read property 'map' of undefined
. What am I doing wrong?
Here's a breakdown of the map
:
So the tree seems to go array --> array --> object but I'm not sure what I need to do to render that.
To start with, look at the docs for Map . Notice that the methods available include entries
, keys
, values
, and forEach
. There is no map method (although one could argue there should be).
Also notice that map is an iterable, so you can do a for (let [key, value] of map){…}
(which is pretty much the same as calling .forEach(…)
or .entries().forEach(…)
).
What you probably want, though, is Array.from(map.entries()).map(…)
or [...map.entries()].map(…)
. .entries()
returns a map iterator of [key, value]
pairs, which can be converted to an array, which has a .map(…)
method.
so your code is pretty close:
return (
<div>{Array.from(leaderboard.entries()).map(([key, value]) => (
<div key={key}>
<div>
<h3>{value.count}</h3>
<h3>{value.node.twitter}</h3>
<hr />
</div>
</div>
))}</div>
)
You can iterate over the keys of your Map:
return (
{[...leaderboard.keys()].map(key => (
<div key={key}>
<h3>{leaderboard.get(key).count}</h3>
<h3>{leaderboard.get(key).node.twitter}</h3>
</div>
))}
);
Check out this codesandbox: https://codesandbox.io/s/o4v0695n5q
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.