Skip to content

How to output the contents of a mapping. #1266

Answered by krakxn
othaime-en asked this question in Q&A
Discussion options

You must be logged in to vote

We cannot iterate through mappings/hash maps unless you precisely know the length of it.

If you do not know the length, you can only manually access it.

If you do know the length, a simple for-loop will be sufficient.

Sample code:

mapping(string => int) temp;
int storeMappingArray [];

// Let's assume you know the length as this is the only way to iterate mappings
tempLength = 5;

for (int i = 0; i < tempLength; i++) {
    storeMappingArray[i] = temp[i]; // This array has every data, which mapping's string key points to
  

But for Solidity, you will never really need this. Manually using the mappings is sufficient, especially since gas fees are so high -- you will hardly use for-loops to …

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by othaime-en
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants