2

Whenever I try to access a mapping in truffle console, I get this error.

mapping(uint256 => uint256[]) public myMapping;

I try:

myContract.deployed().then(function(instance) { return instance.myMapping.call(0) });

Why does the mapping expect two arguments, and what should the second argument be? I just want the value keyed at 0.

  • It looks like you're mapping uint256 to an array of uint256, so it probably expects an index for the array. Maybe get rid of those brackets in the mapping definition? Or just use an array uint256[]? – sfmiller940 Apr 30 '18 at 3:43
4

Because you declared a public mapping, Solidity creates a getter. It looks something like this:

function myMapping(uint256 _index, uint256 _arrayIndex) 
    external
    view
    returns (uint256) 
{
    return myMapping[_index][_arrayIndex];
}

You mapping maps uint256's to uint256[] arrays. As Solidity's standard getter does not return arrays, you will have to specify which element in the array you want to the getter.

To get the first element of the first array in the mapping, use

myContract.deployed().then(function(instance) { 
    return instance.myMapping.call(0,0) 
});

If you want you smart contract to retrieve the array in full, try this function:

function myFullMapping(uint256 _index) 
    external
    view
    returns (uint256[]) 
{
    return myMapping[_index];
}

In JavaScript, you can use this code to get the first array in the mapping:

myContract.deployed().then(function(instance) { 
    return instance.myFullMapping.call(0) 
});
  • Any way to get the whole array from console? – AlwaysQuestioning May 1 '18 at 23:55

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.