new Map() returns error when going through JSON string

This is a problem that is simple, but I have no clue what has gone wrong. I gave it this string:

{"person": "hello"}

and it shot me this error:

Uncaught (in promise) TypeError: Iterator value { is not an entry object

when running this code:

var str = '{"person": "hello"}';
var map = new Map(JSON.parse(str))

This looks like it should work perfectly, the JSON string has double quotes, the colon is there, everything seems in place.

Does anyone know what happened?

Other information:

The string is coming from a fetch.

I manually replace the single quotes with double quotes in some other code (comment if you want me to put it here)

The fetching, JSON string conversion, and everything else go without errors.

1 thought on “new Map() returns error when going through JSON string”

  1. Try this instead:

    var map = new Map(Object.entries(JSON.parse(str)))
    

    Explanation: the Map constructor requires an array of [key, value] tuples, rather than an object. Object.entries can be used to transform an object into such an array.

    Reply

Leave a Comment