6

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} />)

3 Answers 3

12

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} />); } 
Sign up to request clarification or add additional context in comments.

6 Comments

Converting HashMap to array (this needs extra memory and time), then running map over the array....needs you to loop at least twice over the array. It is not very intuitive.
@Sandy any other solution requires additional O(|Entries|) as well tho, and why should it loop twice?
@Sandy the extra memory and time here is irrelevant unless proven otherwise. And if the hashmap is huge enough that looping twice becomes a problem, imagine how worse of a bottleneck that rendering is going to be!
@Dorki: The solution I suggested above should be O(n) with a single time loop. In your suggested solution, it loops once for Array.From function again for .map function. stackoverflow.com/questions/59172980/…
@Emile: Agreed for performance. But why not to avoid it if we can.
|
2

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.

Comments

2

You can derive an array of keys using the built-in Map.prototype.forEach and then use it for .map in your render https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach

let myKeys = []; myHashMap.forEach((value, key) => myKeys.push(key); return ( { myKeys.map((item) => <MyComponent myKey={item} myValue={myHashMap.get(key)}/>) } ) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.