1

This question already has an answer here:

I have a mapping of list of struct (mapping (address => struct[])) I'm having a trouble in how to display all them together in the front end (i'm using React js).

Thnx.

marked as duplicate by Ismael, shane, Achala Dissanayake, Richard Horrocks, flygoing Mar 3 at 11:40

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2

A mapping is a hash table with every possible key mapped to an instance of an element.

Unlike arrays, this means you can't generate an error by referencing an element that doesn't exist, because they all exist. If nothing was written to a given slot then it will return a zero-ish instance (false, 0, empty, 0x0).

Also unlike arrays, it's not possible to iterate the keys or find out how many keys exist, because they all exist.

An important advantage of a mapping is it's ability to access an element by an indentifier in one operation (O(1)). This is very important for smart contracts.

mapping(address => struct) myMap; // id => struct

So, mappings are very useful, but sometimes we also want to be able to iterate the keys or count them. A common pattern is to use an array to hold the list of mappings that exist.

Have a look at "Mapped Struct with Index" over here: Are there well-solved and simple storage patterns for Solidity?

Hope it helps.

0

A mapping is not an array. You cannot iterate over it. It's meant for O(1) operations. Source

If iterating over or simply fetching all known existing structs, I would suggest the following.

1: Store the structs in an array

2: If you want key pair associations with address: use mapping(address => uint256) where uint256 is the index to the struct in the array.

Note: since I do not know your full requirements, there may exist a better strategy. Assess and analyze exactly what your needs are from the smart contract and proceed from there. :)

0

As Rob mentioned about mapping. If you want to show all the data in the front end the best way would be to store the addresses in a seprate array too. In this way you get list of all the address stored in the mapping.

Second step is to get all the addresses from the array and use the for loop at frontend and retrieve the individual data one by one.

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