你如何JSON.stringify一个ES6地图? [英] How do you JSON.stringify an ES6 Map?
问题描述
我想开始使用 ES6地图,而不是JS对象,但我被阻止,因为我无法弄清楚如何JSON.stringify()一个地图。我的密钥保证是字符串,我的值将永远是列表。我真的要写一个包装方法来序列化吗?
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 lists. Do I really have to write a wrapper method to serialize?
推荐答案
你不能。
地图的键可以是任何东西,包括对象。但JSON语法只允许字符串作为键。所以在一般情况下是不可能的。
The keys of a map can be anything, including objects. But JSON syntax only allows strings as keys. So it's impossible in a general case.
我的密钥保证是字符串,我的值将永远是列表
My keys are guaranteed to be strings and my values will always be lists
在这种情况下,您可以使用一个纯对象。它将具有以下优点:
In this case, you can use a plain object. It will have these advantages:
- 它将能够被字符串化为JSON。
- 它
- 可能会更快。
这篇关于你如何JSON.stringify一个ES6地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!