1

I'm trying to convert JSON of the form:

{1: 1, 4: -1}

to a Map where the keys are of type integer.

I managed to do this:

  let myMap = new Map(Object.entries(payload));

but it ends up converting the keys to strings.

What am I doing wrong?

5
  • In a JSON string, the keys are a string. If you are using Object.entries, it means its an Object Commented May 5, 2020 at 21:04
  • 3
    Object keys are always strings.
    – Ori Drori
    Commented May 5, 2020 at 21:04
  • 1
    Where is the JSON string?
    – Taplar
    Commented May 5, 2020 at 21:05
  • I figured that much out; what I wasn't able to figure out is how to get it to convert it to a Map with integer keys.
    – cjm2671
    Commented May 5, 2020 at 21:06
  • are you using JSON.parse if so you can use the reviver option. Commented May 5, 2020 at 21:06

1 Answer 1

5

You can convert the strings to numbers.

const myMap = new Map(Object.entries(payload).map(([k, v]) => ([+k, v]) ));
2
  • This is the solution! Thank you! :)
    – cjm2671
    Commented May 5, 2020 at 21:09
  • @cjm2671 It is my pleasure. Commented May 5, 2020 at 21:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.