I have written a contract. It store struct data based on key. I want to write a get method which accept key and return all the stored data mapped to provided key.

Can anyone help into this


If you are interested in getting access to this data from an external account (e.g. using web3) see Xavier's answer. If you want to read the mapping data from another contract, you could do something like this:

contract myContract {
    struct dataObject {
        uint a;
        address b;
    mapping (uint => dataObject) public myMap;
    function setObject(uint key, uint _a, address _b) {
        myMap[key] = dataObject(_a,_b);

Getting data from another contract:

contract otherContract {
    myContract mc;
    function otherContract (address _mc) {
        mc = myContract(_mc);
    function getMyMapItem (uint key) constant returns (uint, address) {
        return mc.myMap(key);

If you make your mapping public, as in:

struct MyStruct {
    uint fixedLength;
    uint[] variableLength;
    uint fixedLength2;
mapping(uint => MyStruct) public myStructs;

The compiler will create a function to get those values. Then when you call the function from Javascript, the struct is returned as an array of values, such as:

    .then(function (myStructArray) {
        assert.equal(myStructArray.length, 2, "should only have 2 fixed size values");

If you call the public mapping from another contract, it also is returned as an array of values. For instance:

function getStruct(uint key)
    returns (uint fixedLength, uint fixedLength2) {
    return previousContract.myStructs(key);     

Note however that, in both cases, only values of fixed size are returned. You need to access the variable size ones another way, typically with a dedicated method:

function getVariableLengthAt(uint index, uint innerIndex)
    returns (uint) {
    return myStructs[index].variableLength[innerIndex];

Also, there is a limit to the number of fixed size values that can be returned. I found it to be 14. A small project that recaps all this.

  • Xavier, I really welcome your enthusiasm here, however, could you please try to use markdown formatting (esp. for long links) and stop linking external resources but write readable answers here? – Afr Aug 26 '16 at 13:00
  • Ok, edited with code snippets. – Xavier Leprêtre B9lab Aug 26 '16 at 15:17

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.