Home > Software engineering >  Iterable Mapping- how to retreive all the values with For-Loop?
Iterable Mapping- how to retreive all the values with For-Loop?

Time:08-24

From looking at the code below can anyone show me how you'd write a for loop to get all the values in the mapping? Thanks in advance for the help.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

contract IterableMapping {
    mapping(address => uint) public balances;
    mapping(address => bool) public inserted;
    address[] public keys;

    function set(address _addr, uint _bal) external {
        balances[_addr] = _bal;

        if (!inserted[_addr]) {
            inserted[_addr] = true;
            keys.push(_addr);
        }
    }

    function get(uint _index) external view returns (uint) {
        address key = keys[_index];
        return balances[key];
    }

    function first() external view returns (uint) {
        return balances[keys[0]];
    }

    function last() external view returns (uint) {
        return balances[keys[keys.length - 1]];
    }
    ```

CodePudding user response:

oh i see my mistake now with trying to get the bool values. it would be...

function getAllBools() public view returns (bool[] memory) {
    bool[] memory result = new bool[](keys.length);
    for (uint i = 0; i < keys.length; i  ) {
        result[i] = inserted[keys[i]];
    }
    return result;
}

CodePudding user response:

You can loop through balances by using address as key , hereby you will get All the values in the balances Mapping.

  function getAllBalances() public view returns (uint[] memory){
    uint[] memory result = new uint[](keys.length);
    for (uint i = 0; i < keys.length; i  ) {
        result[i] = balances[keys[i]];
    }
    return result;
}

Likewise you can also get values of the inserted mapping

  • Related