In JavaScript, all Objects act a bit like hashmaps. However, the keys to these hashmaps must be strings. If they\'re not, they\'re converted with toString()
. Tha
This is an old question, but ES6 has a feature that may be relevant: Map
Maps can have arbitrary objects as keys, and arbitrary values as values. The main distinction is that the objects used as keys stay unique, even if objects are identical.
Here's an example:
var map = new WeakMap();
var o1 = {x: 1};
var o2 = {x: 1};
map.set(o1, 'first object');
map.set(o2, 'second object');
// The keys are unique despite the objects being identical.
map.get(o1); // 'first object'
map.get(o2); // 'second object'
map.get({x: 1}); // undefined
JSON.stringify
ing the objects wouldn't be able to distinguish between o1
and o2
.
MDN has more info. There's also a WeakMap which doesn't maintain references to the objects used as keys, so they may be garbage collected.
The Traceur compiler doesn't yet have official polyfills for Map and Weakmap, but there is an open pull request with polyfills for both. The code for those polyfills (in case anyone wants to add them individually) are here: Map and WeakMap. Assuming those polyfills work well, you can start using Map or WeakMap today. :)