close

How do you JSON.stringify an ES6 Map?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How do you JSON.stringify an ES6 Map? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How do you JSON.stringify an ES6 Map ?

  1. How do you JSON.stringify an ES6 Map ?

    do you JSON.stringify an ES6 Map Given your example is a simple use case in which keys are going to be simple types, I think this is the easiest way to JSON stringify a Map.

  2. do you JSON.stringify an ES6 Map

    do you JSON.stringify an ES6 Map Given your example is a simple use case in which keys are going to be simple types, I think this is the easiest way to JSON stringify a Map.

Method 1

Both JSON.stringify and JSON.parse support a second argument. replacer and reviver respectively. With replacer and reviver below it’s possible to add support for native Map object, including deeply nested values

function replacer(key, value) {
  if(value instanceof Map) {
    return {
      dataType: 'Map',
      value: Array.from(value.entries()), // or with spread: value: [...value]
    };
  } else {
    return value;
  }
}
function reviver(key, value) {
  if(typeof value === 'object' && value !== null) {
    if (value.dataType === 'Map') {
      return new Map(value.value);
    }
  }
  return value;
}

Usage:

const originalValue = new Map([['a', 1]]);
const str = JSON.stringify(originalValue, replacer);
const newValue = JSON.parse(str, reviver);
console.log(originalValue, newValue);

Deep nesting with combination of Arrays, Objects and Maps

const originalValue = [
  new Map([['a', {
    b: {
      c: new Map([['d', 'text']])
    }
  }]])
];
const str = JSON.stringify(originalValue, replacer);
const newValue = JSON.parse(str, reviver);
console.log(originalValue, newValue);

Method 2

Given your example is a simple use case in which keys are going to be simple types, I think this is the easiest way to JSON stringify a Map.

JSON.stringify(Object.fromEntries(map));

The way I think about the underlying data structure of a Map is as an array of key-value pairs (as arrays themselves). So, something like this:

const myMap = new Map([
     ["key1", "value1"],
     ["key2", "value2"],
     ["key3", "value3"]
]);

Because that underlying data structure is what we find in Object.entries, we can utilize the native JavaScript method of Object.fromEntries() on a Map as we would on an Array:

Object.fromEntries(myMap);

/*
{
     key1: "value1",
     key2: "value2",
     key3: "value3"
}
*/

And then all you’re left with is using JSON.stringify() on the result of that.

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment