Fixed question:
I have a mapping:
mapping (bytes32 => mapping (bytes32 => bytes32[])) items;
With some elements in it:
items["fruits"]["apples"].push("first apple");
items["fruits"]["apples"].push("second apple");
items["fruits"]["apples"].push("third apple");
items["fruits"]["plums"].push("first plum");
items["vegetables"]["carrots"].push("first carrot");
I want to delete all fruits. The code below does not work:
delete items["fruits"]
The error I get is:
Error: Unary operator delete cannot be applied to type mapping(bytes32 => bytes32)
Original question:
I have a mapping:
mapping (bytes32 => mapping (bytes32 => bytes32)) items;
With some elements in it:
items["fruits"]["apples"] = "first apple";
items["fruits"]["apples"] = "second apple";
items["fruits"]["apples"] = "third apple";
items["fruits"]["plums"] = "first plum";
items["vegetables"]["carrot"] = "first carrot";
I want to delete all fruits. The code below does not work:
delete items["fruits"]
The error I get is:
Error: Unary operator delete cannot be applied to type mapping(bytes32 => bytes32)
Best Answer
Unfortunately you can't delete a mapping. From the solidity docs at: http://solidity.readthedocs.io/en/develop/types.html
So you could do something like
delete items[i][j]
but you would need to knowi
andj
in advance.One common pattern is to keep an additional array (e.g.
bytes32[]
) into which you store the keys to your mapping, which you could then iterate over. Or in your case you could keep a mapping from "fruits" to an array of fruits, and then iterate over this when you want to delete all fruits. You would need to maintain these secondary data structures as you add fruits to your main items mapping.Hope this helps!