Hacker News new | ask | show | jobs
by kevincox 1145 days ago
I would argue that all "mapping" structures should use Map these days. Objects should be used only for record/struct data with a fixed set of programmer-named keys.

I think MDN has a good comparison: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

The only real downside of maps is that they don't support JSON serialization. However you can fix this pretty easily by using a map with an overridden `toJSON` for serializable keys.

  class StringMap extends Map {
    toJSON() {
          return Object.fromEntries(this);
    }
  }
4 comments

I'd say the big downside is that they don't support the general looking accessor that I'd wager way way way too many people will accidentally use. Myself definitely being one of them. Would have been better if they didn't "seem" to work with the wrong syntax, at least. But, alas, here we are.
I'm typically using TypeScript so that is more or less a non-issue. But even then it seems like an easy thing to get used to.
Fair. And I didn't say it is a blocker. Just an easy footgun/downside. Is listed on the page linked, even.
That fix is not really a fix. The thing being broken for general serialization is JSON.
And how do deserialize it back to a StringMap without manually doing so? Being able to run a JSON.stringify and then JSON.parse on your state tree seamlessly is important imo.
I’ve been using io-ts for this and been very happy with it. [1] It’s similar to Swift’s Coding protocol in case you’re familiar.

[1] https://gcanti.github.io/io-ts/

What is a "mapping" structure?
Key value, dictionary, ...