Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - swap dictionary changes type to integer

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?

like image 370
ghostrider Avatar asked Aug 23 '26 22:08

ghostrider


1 Answers

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 }));
like image 134
Nina Scholz Avatar answered Aug 25 '26 13:08

Nina Scholz