1

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 !

1 Answer 1

1

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];
  }
}
1
  • Thanks, I don't remember why I avoided to use an array instead of a mapping (maybe was related to problems initializing a Vehicle). I ended up adding such a getter. Jul 25, 2022 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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