0

To read from a mapping in ethers/web3.js, we do this:

const value = await myContract.someMapping(someKey);

We can search up one key/value in the mapping at a time. How can I get ALL values within the mapping instead of just one value? The same applies for arrays where you can retrieve one index of the array:

const value = await myContract.someArray(0);

How can I retrieve the entire array?

2

For an array, you'll need to add a function in your contract, for example:

uint[] private someArray;

function getSomeArray() external view returns (uint[] memory) {
    return someArray;
}

For a mapping, you'll need to extend your contract design, for example:

Every time you add/remove an item to/from the mapping, also add/remove that item from/to an array (and implement a function to return that array, as shown above).

In order to avoid redundancy here, you actually want to change the mapping to map the indexes in that array rather than the actual data.

This would potentially save gas if an item is larger than an index (which is typically of type uint).

| improve this answer | |
  • This seems very convoluted. I know that at some address in memory the hashmap exists, so why can i not just read from that address, perhaps passing in a type definition to get back the data. – Dylan Kerler Oct 8 at 8:32
  • There is a good explanation here: ethereum.stackexchange.com/questions/13167/… – Dylan Kerler Oct 8 at 8:40
  • @DylanKerler: I had to Google-translate that word (convoluted), and now that I have, the answer which you've linked does yield a great deal of it. I just gave you an answer for the array question, and general guidelines (one of several different options) to the mapping question. – goodvibration Oct 8 at 8:48

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.