iterate loop over mapping in solidity

Iterate Loop Over Mapping in Solidity

If you are working on a smart contract in Solidity, you may need to iterate over a mapping at some point. A mapping is a key-value pair data structure, similar to a dictionary in Python or an object in JavaScript. However, unlike an array, you cannot iterate over a mapping using a for loop or a while loop. Instead, you have to use a combination of keys and values to access each item in the mapping.

Method 1: Using an Array of Keys

One way to iterate over a mapping is to create an array of all the keys and then loop through that array to access each value. Here is an example:


      mapping(uint => string) myMapping;
      uint[] myKeys;
      string[] myValues;
      
      function iterateMapping() public {
          for (uint i = 0; i < myKeys.length; i++) {
              myValues.push(myMapping[myKeys[i]]);
          }
      }
    

In this example, we first define a mapping called `myMapping` that maps `uint` keys to `string` values. We also create two arrays, `myKeys` and `myValues`, which we will use to iterate over the mapping. In the `iterateMapping()` function, we loop through the `myKeys` array using a for loop and use each key to access the corresponding value in the mapping. We then push that value onto the `myValues` array.

Method 2: Using a Struct

Another way to iterate over a mapping is to create a struct that stores both the keys and values, and then loop through that struct to access each item. Here is an example:


      mapping(uint => string) myMapping;
      
      struct KeyValue {
          uint key;
          string value;
      }
      
      KeyValue[] myStruct;
      
      function iterateMapping() public {
          for (uint i = 0; i < myStruct.length; i++) {
              myMapping[myStruct[i].key] = myStruct[i].value;
          }
      }
    

In this example, we define a mapping called `myMapping` that maps `uint` keys to `string` values. We also create a struct called `KeyValue` that has two fields: `key` and `value`. We then create an array of `KeyValue` structs called `myStruct`, which we will use to iterate over the mapping. In the `iterateMapping()` function, we loop through the `myStruct` array using a for loop and use each item's key and value to update the corresponding entry in the mapping.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe