fenghaolw
fenghaolw

Reputation: 1

Map/Object in javascript does not support Element as key

My question is how to use Element as a key in vanilla javascript. Before ES6, Object and other map-liked structures use toString() to identify the keys -- which means it is impossible to distinguish Elements.

https://code.google.com/p/closure-library/issues/detail?id=541 is for google closure library, but vanilla javascript has exactly the same issue.

ES6 Map resolves this, which is great! But as usual, how about old browsers that does not support ES6...

Upvotes: 0

Views: 354

Answers (1)

jfriend00
jfriend00

Reputation: 707786

The usual solution to this problem in ES5 is to generate a unique string key (A monotomically increasing number turned into a string works just fine), assign it to the DOM object as a custom property and to then use that string as the key in the Object/Map.

This gives you a unique string, you can use as the map key and if you are given the DOM object again and asked to look it up in the map, you can just check it for the special key and, if found, use it to check the map. If the DOM object does not have the unique key, then it must not have been in one of these maps yet.

Here's a Javascript object that implements this automatically (objectSet): https://github.com/jfriend00/Javascript-Set/blob/master/objectset.js which is related to the code in this answer: Mimicking sets in JavaScript?.

Or, here's a partial polyfill for the ES6 Set object that implements this string key generation automatically when using objects in the Set.

Upvotes: 2

Related Questions