Javascript - swap dictionary changes type to integer

So, I am using this code to invert a dictionary that 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 replace it, I get this:

[object Object] {
    0: "0",
    2: "1",
    4: "2",
    1: "3",
    3: "4"
}

      

so the values โ€‹โ€‹change to string type. Since I want "g_swap_dictionary" to be as generic as possible, how can I fix this?

+3


source to share


1 answer


You can cast the value to a number with a 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 }));
      

Run code


+3


source







All Articles