Mappings + Arrays in Solidity Explained

Kseniya Lifanova
Upstate Interactive
2 min readJun 7, 2018

In our Mappings in Solidity article, we gave a quick breakdown of how mappings work and why they are useful. Another important aspect of mappings that often confuses developers is that they cannot be iterated over.

Say it with me:

“Mappings cannot be iterated over. Mappings cannot be iterated over. Mappings cannot be iterated over.”

This is where arrays come in to save the day. If you think you will need to iterate over information in a mapping, you can create an array of the keys in the mapping. To better explain this, let’s look at an example.

Say you have a User struct:

struct User {
string name;
uint level;
}

You also have a mapping called userStructs to map a User address to their User struct:

mapping (address => User) userStructs;

If you had three users, this is what their mappings would visually look like:

userStructs mapping

Looking at this visual, you would think you could iterate over the mapping to return a list of every address, but you can’t! There is no way to iterate over a mapping to list all the key/value pairs. What you can do is create an array:

address[] public userAddresses;

Every time you add a User you can push their address into the array. Here is a createUser function where you set a User struct with a name and level, and then push their address into the userAddresses array:

function createUser(string name, uint level) {

// set User name using our userStructs mapping
userStructs[msg.sender].name = name;
// set User level using our userStructs mapping
userStructs[msg.sender].level = level;
// push user address into userAddresses array
userAddresses.push(msg.sender);
}

Now you can return the userAddresses array to get a list of all of the addresses:

function getAllUsers() external view returns (address[]) {
return userAddresses;
}

Voila!

In my next article, I’ll be showing you how to write a function to list the addresses of users with a specific property value. In our example, say we wanted a list of user addresses who are in a specific level. How would you do that?

Stay tuned….

We build decentralized applications (DApps) on the Ethereum blockchain

--

--