What is the best way of iterating over a Map object in JSX?
const map = new Map<string, string[]>([
'2023-08-23': ['string1', 'string2'],
'2023-08-24': ['string3', 'string4']
]);
I can do it with a helper function, but I’m wondering if there’s a better way:
const mapMap = () => {
const iterator = map.entries();
const els = [];
for (let i = 0; i < map.size; i++) {
els.push(<div>{iterator.next().value.at(1)}</div>);
}
return els;
}
>Solution :
The Array.from() method is able to iterate the iterator for you, and will produce an array based on what the iterator produces, as well as what you return from the mapping function if you supply one, for example:
Array.from(map.values(), val => <div>{val}</div>);
Here I’m using map.values() instead of map.entries() as in your code you’re only using the value, however, you may want to continue using .entries() (which is implicitly used if you pass the map directly to Array.from()) if you want to specify a key prop, which is best to do in React:
Array.from(map, ([key, val]) => <div key={key}>{val}</div>);