1

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!!

  • Do you mean you want to return the details of every officer saved in the officers mapping? Like return an array of everything in the Officer struct? – vhie Oct 4 '18 at 9:56
  • @vhie Yeah That what I need – dwp Oct 4 '18 at 9:57
2

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]];
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.