tc39 / proposal-object-from-entries

TC39 proposal for Object.fromEntries
https://tc39.github.io/proposal-object-from-entries/
MIT License
318 stars 20 forks source link

new Map() #29

Closed pannous closed 5 years ago

pannous commented 5 years ago

You might want to explain why new Map([['a', 0], ['b', 1]]) isn't sufficient (in some situations).

slikts commented 5 years ago

The Map constructor creates a different data structure (map instead of a plain object), so not sure why this would need explanation.

ljharb commented 5 years ago

a Map and a plain object are different, so this seems self-evident to me; what wording would you suggest that can explain why you might want an object and not a Map?

bathos commented 5 years ago

If you have a collection with an arbitrary set of keys, even if they’re strings, and especially if you intend to add/remove members over time, Map data is likely a more appropriate model than object properties. The rule of thumb is that properties are well-suited to describing interfaces / fixed-shape models, but poorly suited for modeling arbitrary hashes, and Map aims to serve that niche better.

We don’t always get to choose the model. This is one of the things fromEntries is meant to help with. Recognizing that some data is an arbitrary collection, I might prefer to model it using Map. Later that data may need to be passed to an API whose contract expects it to be modeled as an ordinary object though (think query params, headers, etc): externalAPI(Object.fromEntries(myMap)).

Data that comes from or must be serializable to JSON often uses properties to model arbitrary collections. Metaprogramming that reflects on entries is another scenario where we may manipulate or filter entries and then wish to convert them back into an object — for example, when processing objects suitable for passing to Object.defineProperties. For one more example, while not everybody agrees on whether it’s a good idea, arbitrary-key objects may also be chosen deliberately if an author feels they improve API ergonomics.

ljharb commented 5 years ago

This seems great - does someone want to volunteer to add this to the readme?