Deb
Deb

Reputation: 389

Mapping of Mapping in Solidity

So I am trying to create data structure, where a byte32 is mapped to an array of addresses, each address is mapped to a uint.

I am thinking of the below method, but it does not seem right:

mapping (byte32 => mapping (address[] => uint))

If possible, please help me with this. If the issue description is not clear enough, feel free to let me know.

Example: There is a property, which is mapped to an array of owners(address) (owners of the property) and each owner is mapped to the stake(uint) they own in that property.

Upvotes: 5

Views: 9320

Answers (2)

Joseph T F
Joseph T F

Reputation: 801

Example: There is a property, which is mapped to an array of owners(address) (owners of the property) and each owner is mapped to the stake(uint) they own in that property.

A way to implement this is like below using struct

struct Division {
    address owner;
    uint256 plots;
}

mapping(bytes32 => Division[]) Properties;    

function addDivision(bytes32 _property, address _owner, uint256 _plots) 
   public returns (bool success) {


    Division memory currentEntry;

    currentEntry.owner = _owner;
    currentEntry.plots = _plots;


    Properties[_property].push(currentEntry);

    return true;
}


function getPlot(bytes32 _property, address _owner) public view returns (uint) {


    for(uint i = 0; i < Properties[_property].length;  i++) {
        if(Properties[_property][i].owner == _owner)
          return Properties[_property][i].plots;
        }
    return 9999;
}

Upvotes: 2

Shane Fontaine
Shane Fontaine

Reputation: 2439

Yes that is possible and it is the advised way to do it.

The thing to remember is that you cannot simply iterate over the items (like you would an array), but if your application has no need for that then you are alright.

Another thing to consider is creating a struct with IDs and attributes, but, again, it is up to your specific application.

Upvotes: 1

Related Questions