1

Here are a few relevant code snippets from my smart contract

  struct Constituency{
    uint16 id;
    string name;
    uint64[] cans;
  }

  mapping(uint => Constituency) public constituencies;

  function newConstituency(string memory _name) private{
    uint64[] memory tmp;
    constituencies[concount] = Constituency(concount, _name, tmp);
    concount++;
  }

  constructor() public{
    newConstituency("Bikini Bottom");
    constituencies[0].cans = [1,2,3];
  }

And here's the web3 snippet I'm using to access elements from the constituencies mapping:

election.methods.constituencies(0).call({from : defaultAccount},function(e,r){ console.log(r) })

Here is the response it gives out:

Result { '0': '0', '1': 'Bikini Bottom', id: '0', name: 'Bikini Bottom' }

As you can see, it simply does not mention the array. What can I do to fix this?

  • To begin with, change constituencies[0].cans = [1,2,3]; to constituencies[0].cans.push(1); constituencies[0].cans.push(2); constituencies[0].cans.push(3); – goodvibration Aug 16 at 6:21
0

You gotta make your own getter function. Web3 can't handle 2D array returns like that. Here's what you need:

  function getConstituency(uint _id) external view returns (uint, string memory, uint64[]) {
      return (constituencies[_id].id, constituencies[_id].name, constituencies[_id].cans);
  }

But there's one more thing: I'm showing you an example based on the code you provided, but you should really get rid of the id inside the struct. It's redundant since it is the same number used for the mapping and the same position of the constituency in the array. It's just using up storage with no need.

Hope it helps!

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.