Solidity Mapping – How to Delete or Remove a Key from Mapping

mappingsolidity

I have the following map:

mapping (string => Category) categoryMap;

Let's say the key was mistyped, so I want to remove the key and add a correct one, how would I do that?

Function would be

  function updateCategoryLabel(string _newCategoryLabel, string _oldCategoryLabel) {
    categoryMap[_oldCategoryLabel].label = _newCategoryLabel;
    Category tmpCategory = categoryMap[_oldCategoryLabel];
    // Delete Key
    // create new key from _newCategoryLabel
      }

Thanks

Edit:

Here is what I was doing:

  function updateCategoryLabel(string _newCategoryLabel, string _oldCategoryLabel) {
    categoryMap[_oldCategoryLabel].label = _newCategoryLabel;
    Category tmpCategory = categoryMap[_oldCategoryLabel];
    delete categoryMap[_oldCategoryLabel];
    categoryMap[_newCategoryLabel] = tmpCategory;
  }

Category struct

  struct Category {
    string label;
    uint percent;
    address[] userList;
  }

Best Answer

Try this:

function updateCategoryLabel(string _newCategoryLabel, string _oldCategoryLabel) {
    categoryMap[_newCategoryLabel] = categoryMap[_oldCategoryLabel];
    delete categoryMap[_oldCategoryLabel];
}
Related Topic