nuvio nuvio - 11 days ago 5
Javascript Question

ES7 Map JSON adds square brackets

I am using

core-js
for the Map collection, since it seems ES7
Map
has a Map to JSON functionality which does not exist in ES6
Map
.

(ES6): JSON.stringify(new Map().set('myKey1', 'val123').set('myKey2', 'val456')); => {}


Although ES 7 seems to add unnecessary square brackets to the key value pairs

Eg (ES7): JSON.stringify(new Map().set('myKey1', 'val123').set('myKey2', 'val456')); => [["myKey1","val123"],["myKey2","val456"]]


when I would expect this instead:

{"myKey1": "val123","myKey2":"val456"}


Please help!

EDIT:
I realised I posted a bad JSON, but that was just a typing error when writing the question.

The point is, beacause I am using TypeScript to create a new
Map
of string key -value pairs like

new Map<string, string>()


I would expect the JSON output of a such Map to be
{"myKey1": "val123","myKey2":"val456"}
so I would ask for suggestions on how do I get the desired outcome.

Answer

This is because the default map iterator is .entries which yields key-value pairs. If you want to use another iterator, you have to provide or program it, for example:

function *flatEntries(map) {
    for (let [k, v] of map) {
        yield k;
        yield v;
    }
}


let m = new Map().set('myKey1', 'val123').set('myKey2', 'val456');
let s = JSON.stringify([...flatEntries(m)]);

console.log(s)