Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React loop through map and display components

So I have a unique situation,

in my States I don't have a regular list that I can do map and then in each iteration to display a component, for example:

list.map(shape => <Shape {...shape} />)

But I have an Hash Map. I need to know the key and the value so I'll have the necessary information to display it as component. So I found a nice method: entries() that returns an Iterator, but how could I iterate it in a way that I could display new components inline?

Something like that in pseudo code:

myHashMap.entries().toList().map((key, value) => <MyComponent myKey={key} myValue={value} />)

like image 922
Dorki Avatar asked Aug 28 '26 15:08

Dorki


2 Answers

You guys gave great answers, but I found the simplest syntax:

Array.from(myHashMap.entries()).map((entry) => {
    const [key, value] = entry;
    return (<MyComponent myKey={key} myValue={value} />);
}
like image 179
Dorki Avatar answered Aug 31 '26 07:08

Dorki


Map function basically loops and returns result of each loop as an array. So basically all you need is an array of components in the end. There are just different routes to achieve it.

Converting HashMap to an array and running a map on it is slower. Please avoid that. Below code will loop through just once.

function getComponents(myHashMap) {
  const comps = [];
  myHashMap.forEach((value, key) => comps.push(<MyComponent myKey={key} myValue={value} />));
  return comps;
}

Hope it helps.

like image 27
Sandy Avatar answered Aug 31 '26 05:08

Sandy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!