nuvio nuvio - 1 year ago 131
Javascript Question

ES7 Map JSON adds square brackets

I am using

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

(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!

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
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 Source

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)]);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download