How can I reverse the key and value of the map?
for example, {1:a , 2:b , 3:c} => {a:1 ,b:2 ,c:3}
CodePudding user response:
You can do this:
const items = {1:'a' , 2:'b' , 3:'c'};
void main() {
final inverted = items.map((key, value) => MapEntry(value, key));
print(inverted);
}
It logs
{a: 1, b: 2, c: 3}
CodePudding user response:
Try this piece of code:
Map<int, String> map = {1: "a", 2: "b", 3: "c"};
Iterable<String> values = map.values;
Iterable<int> keys = map.keys;
Map<String, int> reversedMap = Map.fromIterables(values, keys);
print(reversedMap); // {a:1 ,b:2 ,c:3}
CodePudding user response:
Try this example. As simple as efficient.
var obj = {1:'x',2:'y',3:'z'};
var newObj = {};
for(let o in obj){
newObj[obj[o]] = o;
}
console.log(newObj)
Please do let me know thoughts on this.