Solidity Mapping – How to Access Nested Struct Mapping Members

mappingsoliditystruct

I have 2 structs like this :

struct Wheel {
    uint radius;
    uint width;
}

struct Vehicle {
    string model;
    uint wheelCount;
    mapping(uint => Wheel) wheels;
}

uint public vehicleCount = 0;
mapping(uint => Draw) public vehicles;

function getWheel( uint vid, uint wid) external view returns(Wheel memory) {
    return vehicles[vid].wheels[wid];
}

From my reactjs app I loop "for 1 to vehicleCount" and call contract.vehicle(i).
I get the vehicle structure but without the wheels mapping.

To get the wheels I then loop "for 1 to wheelCount" in each vehicle loop and use the getter I wrote (getWheel( i, j)).

Is there another/better way to get the wheels ? (maybe directly through a custom vehicle getter that would return a struct containing the wheels map).

Thanks !

Best Answer

I think overall the best solution is to rewrite the struct by using an array instead of a mapping:

struct Vehicle {
    string model;
    uint wheelCount;
    uint256[] wheels;
}

If you don't want to change the existing contract, you can add a getter like this:

function getVehicle(uint256 vid) external view returns(string memory model, uint256 wheelCount, uint256[] memory wheels) {
  model = vehicles[vid].model;
  wheelCount = vehicles[vid].wheelCount;
  wheels = new uint256[](wheelCount);
  for (uint256 i=0; i < wheelCount; i++) {
    wheels[i] = vehicles[vid].wheels[i];
  }
}
Related Topic