How to output the contents of a mapping. #1266
-
Hello guys. Is there a way i could iterate through a mapping and output all of its contents in the console (in solidity of course) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
@othaime-en You cannot directly iterate through the mapping, because there is no such thing as when you insert data in the mapping contract Test {
mapping (uint256 => uint256) public data;
function iterate() public {
// if you want to store in a local array and return it.
uint256[] memory localData = new unit[](<length-of-mapping>);
// if you want to iterate.
for(uint256 i = 0; i < length-of-mapping; i++) {
data[i]; // but we cannot print unless you are using a hardhat for it
}
}
} And here One more important thing is that mapping will always be a state variable and we cannot create a local (memory) copy of it, so it will also change the state of the blockchain it is a very gas-intensive task and can fail the transaction if the gas cost exceed the block gas cost limit. |
Beta Was this translation helpful? Give feedback.
-
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 iterate through databases such as arrays. Hope this helps! |
Beta Was this translation helpful? Give feedback.
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:
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 …