3 ms·
Goodbye object literals too, apparently.
by WorldWideWayne 12y ago
Goodbye object literals too, apparently.
- z1mm32m4n 12y agoI can potentially imagine a helper function like `mapFromObject`, but yeah I agree with you. That syntax is disheartening. Enough to make me want to keep using `hasOwnProperty`.
- masklinn 12y agoThe map constructor simply takes an iterable.
- nawitus 12y agoSomeone asked for this elsewhere, it's really simple. Kinda odd that it's not in the standard, though. EDIT: It's because Maps preserve insertion order, so the standard doesn't advocate use like this. var objectToMap = x => new Map(Object.keys(x).map(o => [o, x[o]]));
- pedrow 12y agoThe intention is not to replace all 'map-like' uses of Object with Map. This MDN link explains clearly I think: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Objects_and_maps_compared https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- WorldWideWayne 12y agoThank you. Here is the advice from that page: Use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type. Use objects when there is logic that operates on individual elements. Scroll down a bit and their first example is a Map with one string key, one object key and one function key... I understand that Objects can only have keys that can be represented as a string. I do not understand why they say to use a Map when all keys are the same type and all values are the same type. Also, how would "logic that operates on individual elements" differ between a Map and an Object?
- shawnz 12y ago> I do not understand why they say to use a Map when all keys are the same type and all values are the same type. Also, how would "logic that operates on individual elements" differ between a Map and an Object? An object is for describing the different properties of one thing. For example: var myCar = { make: "Nissan", model: "Altima", colour: "Black" }; See how each value is a different type of data (even though technically they are all strings)? Here, it would make no sense to enumerate over each property because they all have different meanings. Rather, you would use them individually based on what information you needed. On the other hand, a map is for describing a single property for many things: var manufacturers = new Map([ ["Altima", "Nissan"], ["Acura", "Nissan"], ["Accord", "Honda"], ["Camry", "Toyota"] ]); Here, each key and each value are all the same type of data as one another (models and makes, respectively). Because of that, it would make sense to have the structure be enumerable. Similarly unlike an object, it wouldn't make sense to assume that a particular known key exists, e.g. with hardcoded references to certain keys.