Home > Enterprise >  Renaming "key" in map using `Dart`
Renaming "key" in map using `Dart`

Time:09-13

My intention is to format the name key in an existing Map value. Supposed the current key value is in UpperCase but I wanted to make it LowerCase

From this

Map<String, String> foo = {
       "A" : "valueOne", 
       "B" : "valueTwo",
};

print(foo); // output: {"A" : "valueOne", "B" : "valueTwo"}

To this

print(foo); // output: {"a" : "valueOne", "b" : "valueTwo"}

Here's the method I tried:

Map<String, String> foo = {
       "A" : "valueOne", 
       "B" : "valueTwo",
};

foo.forEach((key, value) {
    key = key.toString().toLowerCase();
    value = value;
});

... something something

also tried to assign the forEach as a value

Map<String, String> foo = {
       "A" : "valueOne", 
       "B" : "valueTwo",
};

var bar = foo.forEach((key, value) {
    key = key.toString().toLowerCase();
    value = value;
});

print(bar); // Failed because forEach Datatype is `void`

... something something

also tried

Map<String, String> foo = {
       "A" : "valueOne", 
       "B" : "valueTwo",
};

foo.forEach((key, value) {
    key = key.toString().toLowerCase();
    value = value;

    Map<String, String> bar = {key: value};

    print(bar); // `Output: {a: valueOne} {b: valueTwo}` <- is not what I was looking for.
});

... something something

Any suggestions on what to do Next?

CodePudding user response:

I found the answer already.

  Map<String, String> foo = {
    "A": "valueOne",
    "B": "valueTwo",
  };

  Map<String, dynamic> bar = {};

  foo.keys.toList().forEach((key) {
    bar.addAll({key.toString().toLowerCase(): foo[key]});
  });

  print(bar);
}

CodePudding user response:

First of all, you cannot change a key, you have to remove the old key and add a new key instead.

You can then choose to either update the existing map, or build a new one.

Creating a new one is simpler:

var newMap = {for (var e in oldMap.entries) e.key.toLowerCase() : e.value};

We ignore the risk of having existing keys which are equal after calling toLowerCase, like "Foo", "FOO" and "foo".

Updating the existing map is trickier, but if we ignore the same risks, it can be something like:

// Snapshot the keys to avoid concurrent modification error when iterating.
for (var e in map.entries.toList()) { 
  var key = e.key;
  var lc = key.toLowerCase();
  if (lc != key) {
    map[lc] = e.value;
    map.remove(key); 
  }
}

Alternatively, use a CanonicalizedMap to begin with, which does the lower-casing for you (and allows you to look up with any casing of the same text).

  • Related