solidity – How to Delete an Element from Mapping of Address to Struct Array – Detailed Method

remixsolidity

I have the following struct and mapping.

struct consumeID{
    address consumerGatewayID;
    string serviceConsumerID; 
}
mapping(address=>consumeID[]) public pendingAccessRequests;

I want to add and delete elements from the mapping.

For adding elements i tried something like this:

pendingAccessRequests[_producerGatewayID].push(consumeID(_consumerGatewayID, _serviceConsumerID));

Can anyone help me with logic to delete elementsfrom that mapping?

Best Answer

You can use delete pendingAccessRequest[key] to remove whole elements from the mapping.

// Before deleting pendingAccessRequest[key] is an array;

delete pendingAccessRequest[key];

// After deleting pendingAccessRequest[key] empty array

If you want to remove an element from the array, you can do that by delete pendingAccessRequest[key][position] by indicating the position. But you should be aware that this will not resize the array, it will replace the deleted position with zero bytes.

// If we have data = [11, 12, 13, 14]
delete data[2];
// After deleting we have data = [11, 12, 0, 14]
Related Topic