I’d like to start using ES6 Map instead of JS objects but I’m being held back because I can’t figure out how to JSON.stringify()
a Map
. My keys are guaranteed to be strings and my values will always be listed. Do I really have to write a wrapper method to serialize?
Advertisement
Answer
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
JavaScript
x
11
11
1
function replacer(key, value) {
2
if(value instanceof Map) {
3
return {
4
dataType: 'Map',
5
value: Array.from(value.entries()), // or with spread: value: [...value]
6
};
7
} else {
8
return value;
9
}
10
}
11
JavaScript
1
9
1
function reviver(key, value) {
2
if(typeof value === 'object' && value !== null) {
3
if (value.dataType === 'Map') {
4
return new Map(value.value);
5
}
6
}
7
return value;
8
}
9
Usage:
JavaScript
1
5
1
const originalValue = new Map([['a', 1]]);
2
const str = JSON.stringify(originalValue, replacer);
3
const newValue = JSON.parse(str, reviver);
4
console.log(originalValue, newValue);
5
Deep nesting with combination of Arrays, Objects and Maps
JavaScript
1
11
11
1
const originalValue = [
2
new Map([['a', {
3
b: {
4
c: new Map([['d', 'text']])
5
}
6
}]])
7
];
8
const str = JSON.stringify(originalValue, replacer);
9
const newValue = JSON.parse(str, reviver);
10
console.log(originalValue, newValue);
11