What is a practical use of objects as keys within JS Map dataype?

Phil Blunt :

Slightly afraid of down-votes as this could be seen as a matter of opinion, but it's not clear how or where else to post this on Stack Exchange, so here I go... I certainly think it's a question that adds value here, at least.

I've recently been reading into Javascript's Map datatype (NOT the map() array method). MDN Reference

I've read and followed various tutorials/articles showing the similarities and differences between Maps, Arrays and 'standard' Objects. One unique property of Maps is that you can use any datatype as a key, including an Object.

There are many examples out there, such as this one from Tania Rascia

// Create an object
const objAsKey = { foo: 'bar' }

const map = new Map()

// Set this object as the key of a Map
map.set(objAsKey, 'What will happen?')

Here's the console output:

key: {foo: "bar"}
value: "What will happen?"

What I'm asking is, what is a benefit of this possibility? Why would I ever need to use an object as a key?

Thanks so much in advance for any light anybody can shine on this.

Hope I don't get down-voted to oblivion!

Kyle Simpson :

From my tweets on the subject:

Say you have an object (like a DOM element) that you want to associate some data with, but you don't want to modify the object to add the data directly to it. So you use a Map with the object as key and your associated data as value.

typically, you'd want to use a WeakMap for this, so that if the original object goes away (GCd) the data is also released.

but a reason to use map instead of weakmap is that map is iterable and weakmap isn't.

so if you're willing to trade out that you need to do more manual work to manage the map entries (for cleaner GC), then you get the ability to enumerate all the entries of the map, which can be useful in certain cases.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=10464&siteId=1