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?


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]
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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