1

I have the following code:

const x = new Map([['key', 'value']])

Now, I want to stringify this. I used the following:

JSON.stringify(x)

...which gave me an empty object.

How do you actually perform the stringification on new Map()? Is it something like you first turn it into an object and then stringify it?

I am expecting the output to be {"key": "value"}.

3
  • 2
    try JSON.stringify([...x]) Commented Mar 22, 2019 at 12:28
  • @ThanveerShah I thought Map & Object are similar so I was expecting object sort of output.
    – Axel
    Commented Mar 22, 2019 at 12:30
  • Yes they are similar Commented Mar 22, 2019 at 12:31

2 Answers 2

3

You could get the array from the map and stringify the result.

const x = new Map([['key', 'value']])

console.log(JSON.stringify(Array.from(x)));

4
  • I was expecting output to be {"key": "value"} as Object and Map are similar. Isn't this how it should be or not?
    – Axel
    Commented Mar 22, 2019 at 12:32
  • @Sanjay try -> [...m.entries()].reduce((a, v) => (a[v[0]] = v[1],a), {});
    – Keith
    Commented Mar 22, 2019 at 12:33
  • @Keith So you've got to loop and stuff everytime. This sucks but thanks a lot for the solution.
    – Axel
    Commented Mar 22, 2019 at 12:35
  • it is exactly in the format, you can take it as whole map for the constructor. Commented Mar 22, 2019 at 12:35
0

If you want to access direct value then you can use this in loop.

console.log(JSON.stringify(x.get('key')));

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