Access Javascript Map Similarly To Plain Object
Solution 1:
If you want access to the actual values of the Map
object, then you have to use .get()
and .set()
or various iterators.
var m = new Map();
m.set("test", "foo");
console.log(m.get("test")); // "foo"
Regular property access on a Map
such as:
m["test"] = "foo"
just sets a regular property on the object - it does not affect the actual map data structure.
I imagine it was done this way so that you can access the Map
object properties separately from the members of the Map
data structure and the two shall not be confused with one another.
In addition, regular properties will only accept a string as the property name so you can't use a regular property to index an object. But, map objects have that capability when using .set()
and .get()
.
You asked for a "definitive" answer to this. In the ES6 specification, you can look at what .set()
does and see that it operates on the [[MapData]]
internal slot which is certainly different than the properties of an object. And, likewise, there is no where in that spec where it says that using normal property access would access the internal object [[MapData]]
. So, you'll have to just see that normal property access is describe for an Object. A Map
is an Object
and there's nothing in the Map
specification that says that normal property access should act any different than it does for any other object. In fact, it has to act the same for all the methods on the Map
object or they wouldn't work if you happened to put an item in the Map
with the same key as a method name. So, you're proof consists of this:
- A simple test will show you that property access does not put anything in the
Map
itself, only a regular property. - The spec describes a
Map
as an object. - The spec describes how
.get()
and.set()
operate on the internal slot[[MapData]]
. - There's nothing in the spec that says property access on a
Map
object should work any different than it always does. - If property access did access the
MapData
, then you would not be able to access methods if you happened to put a key in theMap
that conflicted with a method name - that would be a mess if that was the case.
Post a Comment for "Access Javascript Map Similarly To Plain Object"