Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to retrieve all items from a mapping in efficient manner #1

Open
swswsw opened this issue Sep 30, 2022 · 3 comments
Open

How to retrieve all items from a mapping in efficient manner #1

swswsw opened this issue Sep 30, 2022 · 3 comments

Comments

@swswsw
Copy link

swswsw commented Sep 30, 2022

for example:

    struct Item {
        uint id;
        string nameOfItem;
        string typeofItem;
        uint value;
    }
    
   struct User {
        address userAddress;
        string email;
    }

    mapping (address => Item[]) public userItems;

It is easy to get Item based given user address. What if we want to get all user address? Or if we want to get all the items?

@MatheusDaros
Copy link
Contributor

Hello @swswsw
Thanks for the question.
Unfortunately it is impossible to directly return all the elements in a mapping or even in a array using solidity.
A possible workaround would be keeping an array to track all the addresses that have been populated inside the mapping, and then iterating through the array to get all elements.

@luksgrin
Copy link

luksgrin commented Oct 2, 2022

It could be possible to implement a library called "extended mapping", consisting of a mapping with extended methods such as python's .items(), .keys(), .values()...

@MatheusDaros
Copy link
Contributor

Yes, it would. The problem is that those constructions spend huge amounts of space to map it all out. It is advisable to, whenever possible, do all of these operations offchain, and include onchain only the inevitable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants