1

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?

2 Answers 2

3

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]
2

In addition to Ismael's answer, you actually CAN delete from array with shrinking. If order does not matter in your case, you may move element from last position to the one you want to delete, and then simply do .pop() on the array. This essentially picks last item from the array and shrinks it by one. See example based on Ismael's:

// Assume we have data: [11, 12, 13, 14] and need to delete 13
data[2] = data[data.length - 1];
// data: [11, 12, 14, 14]
data.pop()
// data: [11, 12, 14]

Wondering if this is cost-efficient and provides any viable gas refund benefits

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.