Solidity – How to Return Mapping Data

solidity

I have a problem like this. I am very new to ethereum stuff. I have built a smart contract like this.

pragma solidity ^0.4.17;

contract TrafficFine{
    struct Officer {
        string firstName ;
        string lastName;
        address account;
    }

    address public manager;
    uint public numberOfOffiers;

    mapping(address=>Officer) public officers;

    modifier restricted(){
        require(msg.sender == manager);      
        _;
    }

    constructor () public{
        manager = msg.sender;
        //fineAmount =0;
    }

    function addOfficer(string firstName,string lastName,address officer) public  restricted{

        require(officer!=officers[officer].account);

        Officer  memory newOfficer = Officer({
            firstName:firstName,
            lastName:lastName,
            account:officer
        });

        officers[officer] = newOfficer;
        numberOfOffiers++;
    }

    function getOfficer(address officer) public view returns(address){
        return officers[officer].account;
    }


}

I want to get the details of all officers. I searched in the net to find a solution to return details of a mapping. But I was unable to do it. Can someone help me to do this? Thank You!!

Best Answer

The smart contract itself does not know what has been stored in the mapping, as it does not maintain the list of set keys.

You need to create

  • An additional array where you add all keys that has been set - array contains keys of the map

  • Getter function that returns the length of this array, so that you can iterate through the all keys

  • Getter function that allows to query array index Nth item:

Example for the last one:

 function getNthOfficerName(uint n) returns(string) {
    return officers[storedKeys[n]];
 }
Related Topic