1

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;
  }
3
  • The answer below is correct per say (i.e., for the given question), but if we look beyond this question - you don't need to delete the entry (key + value) if you plan to override it immediately after. Nov 11, 2018 at 12:24
  • @goodvibration but then how do I update the key. Let's say the og key is "prson" and I want the key to be "person" but have the same value, how would I just update/edit the key? Nov 11, 2018 at 12:26
  • Then you wouldn't be updating the value of the existing key ("prson"), you'd be mapping a value to a new key ("person"). Nov 11, 2018 at 12:27

2 Answers 2

1

Try this:

function updateCategoryLabel(string _newCategoryLabel, string _oldCategoryLabel) {
    categoryMap[_newCategoryLabel] = categoryMap[_oldCategoryLabel];
    delete categoryMap[_oldCategoryLabel];
}
1
delete categoryMap[_oldCategoryLabel];
9
  • You might want to add that technically, there's no need to delete the entry (key + value) if the plan is to override it immediately after. Nov 11, 2018 at 12:26
  • @Edmund Edgar that's what I was doing so far, but doesn't it just delete the value linked to the key _oldCategoryLabel when you do so? Nov 11, 2018 at 12:27
  • @iNukeLaPeste: You'd need to copy that value first. Nov 11, 2018 at 12:28
  • @goodvibration that's what I did. I updated my main post! Nov 11, 2018 at 12:32
  • @iNukeLaPeste: I can see your code in your question. It's all messed up - you are trying to assign the new key to the old key's value. If they're not of the same type, then this code won't even compile. If they are of the same type, then - even worse - you'll probably get extremely undesired behavior, without understanding why. Nov 11, 2018 at 12:33

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.