So I am using this code for inverting a dictionary - which I found on SO.
function g_swap_dictionary ( dict ) {
let ret = {};
for(var key in dict){
ret[dict[key]] = key;
}
return ret;
}
But if I have this dictionary :
[object Object] {
0: 0,
1: 2,
2: 4,
3: 1,
4: 3
}
and swap it I get this :
[object Object] {
0: "0",
2: "1",
4: "2",
1: "3",
3: "4"
}
so values change to string type. Since I want 'g_swap_dictionary' to be as generic as possible - how can I fix that?
You could cast the value to number with an unary plus +
ret[dict[key]] = +key;
// ^
function g_swap_dictionary (dict) {
let ret = {};
for(var key in dict){
ret[dict[key]] = +key;
}
return ret;
}
console.log(g_swap_dictionary({0: 0, 1: 2, 2: 4, 3: 1, 4: 3 }));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With